UNPKG

2.13 kBPlain TextView Raw
1import * as tsm from 'ts-morph';
2import {
3 DeclarationKinds,
4 VariableDeclaration,
5} from '../types/module-declarations';
6import { formatVariableSignature } from './format';
7import { getApparentType } from './get-apparent-type';
8import { getJSDocs } from './get-jsdocs';
9import { hasVarLikeType } from './has-var-like-type';
10import { SourceProvider } from './source-provider';
11
12export function isVariable(
13 declaration: tsm.Node
14): declaration is tsm.VariableDeclaration {
15 return (
16 tsm.Node.isVariableDeclaration(declaration) &&
17 hasVarLikeType(declaration)
18 );
19}
20
21export function newVariable({
22 id,
23 name,
24 declaration,
25 getSource,
26 suggestedType,
27}: {
28 id: string;
29 name: string;
30 declaration: tsm.VariableDeclaration;
31 getSource: SourceProvider;
32 suggestedType?: string;
33}): VariableDeclaration {
34 const kind = DeclarationKinds.VariableDeclaration;
35 const docs = getJSDocs({ declaration });
36 const source = getSource({ declaration });
37 const variableKind = getVariableKind({ declaration });
38 const type = getVariableType({ declaration, suggestedType });
39 const signature = getVariableSignature({ variableKind, name, type });
40
41 return {
42 kind,
43 id,
44 name,
45 docs,
46 source,
47 signature,
48 variableKind,
49 type,
50 };
51}
52
53function getVariableKind({
54 declaration,
55}: {
56 declaration: tsm.VariableDeclaration;
57}): string {
58 return declaration
59 .getVariableStatementOrThrow()
60 .getDeclarationKind()
61 .toString();
62}
63
64function getVariableType({
65 declaration,
66 suggestedType = 'any',
67}: {
68 declaration: tsm.VariableDeclaration;
69 suggestedType?: string;
70}): string {
71 const apparentType = getApparentType({ declaration });
72 return apparentType !== 'any' ? apparentType : suggestedType;
73}
74
75export function getVariableSignature({
76 variableKind,
77 name,
78 type,
79}: {
80 variableKind: string;
81 name: string;
82 type: string;
83}): string {
84 const signature = `${variableKind} ${name}: ${type}`;
85 return formatVariableSignature(signature);
86}