/
getTSType.js
381 lines (338 loc) · 9.79 KB
/
getTSType.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
import getPropertyName from './getPropertyName';
import printValue from './printValue';
import recast from 'recast';
import getTypeAnnotation from '../utils/getTypeAnnotation';
import resolveToValue from '../utils/resolveToValue';
import { resolveObjectToNameArray } from '../utils/resolveObjectKeysToArray';
import getTypeParameters, {
type TypeParameters,
} from '../utils/getTypeParameters';
import type {
FlowTypeDescriptor,
FlowElementsType,
FlowFunctionSignatureType,
FlowObjectSignatureType,
} from '../types';
const {
types: { namedTypes: types },
} = recast;
const tsTypes = {
TSAnyKeyword: 'any',
TSBooleanKeyword: 'boolean',
TSUnknownKeyword: 'unknown',
TSNeverKeyword: 'never',
TSNullKeyword: 'null',
TSUndefinedKeyword: 'undefined',
TSNumberKeyword: 'number',
TSStringKeyword: 'string',
TSSymbolKeyword: 'symbol',
TSThisType: 'this',
TSObjectKeyword: 'object',
TSVoidKeyword: 'void',
};
const namedTypes = {
TSArrayType: handleTSArrayType,
TSTypeReference: handleTSTypeReference,
TSTypeLiteral: handleTSTypeLiteral,
TSInterfaceDeclaration: handleTSInterfaceDeclaration,
TSUnionType: handleTSUnionType,
TSFunctionType: handleTSFunctionType,
TSIntersectionType: handleTSIntersectionType,
TSTupleType: handleTSTupleType,
TSTypeQuery: handleTSTypeQuery,
TSTypeOperator: handleTSTypeOperator,
};
function handleTSArrayType(
path: NodePath,
typeParams: ?TypeParameters,
): FlowElementsType {
return {
name: 'Array',
elements: [getTSTypeWithResolvedTypes(path.get('elementType'), typeParams)],
raw: printValue(path),
};
}
function handleTSTypeReference(
path: NodePath,
typeParams: ?TypeParameters,
): ?FlowTypeDescriptor {
let type: FlowTypeDescriptor;
if (types.TSQualifiedName.check(path.node.typeName)) {
const typeName = path.get('typeName');
if (typeName.node.left.name === 'React') {
type = {
name: `${typeName.node.left.name}${typeName.node.right.name}`,
raw: printValue(typeName),
};
} else {
type = { name: printValue(typeName).replace(/<.*>$/, '') };
}
} else {
type = { name: path.node.typeName.name };
}
const resolvedPath =
(typeParams && typeParams[type.name]) ||
resolveToValue(path.get('typeName'));
if (path.node.typeParameters && resolvedPath.node.typeParameters) {
typeParams = getTypeParameters(
resolvedPath.get('typeParameters'),
path.get('typeParameters'),
typeParams,
);
}
if (typeParams && typeParams[type.name]) {
type = getTSTypeWithResolvedTypes(resolvedPath, typeParams);
}
if (resolvedPath && resolvedPath.node.typeAnnotation) {
type = getTSTypeWithResolvedTypes(
resolvedPath.get('typeAnnotation'),
typeParams,
);
} else if (path.node.typeParameters) {
const params = path.get('typeParameters').get('params');
type = {
...type,
elements: params.map(param =>
getTSTypeWithResolvedTypes(param, typeParams),
),
raw: printValue(path),
};
}
return type;
}
function getTSTypeWithRequirements(
path: NodePath,
typeParams: ?TypeParameters,
): FlowTypeDescriptor {
const type = getTSTypeWithResolvedTypes(path, typeParams);
type.required = !path.parentPath.node.optional;
return type;
}
function handleTSTypeLiteral(
path: NodePath,
typeParams: ?TypeParameters,
): FlowTypeDescriptor {
const type: FlowObjectSignatureType = {
name: 'signature',
type: 'object',
raw: printValue(path),
signature: { properties: [] },
};
path.get('members').each(param => {
if (
types.TSPropertySignature.check(param.node) ||
types.TSMethodSignature.check(param.node)
) {
type.signature.properties.push({
key: getPropertyName(param),
value: getTSTypeWithRequirements(
param.get('typeAnnotation'),
typeParams,
),
});
} else if (types.TSCallSignatureDeclaration.check(param.node)) {
type.signature.constructor = handleTSFunctionType(param, typeParams);
} else if (types.TSIndexSignature.check(param.node)) {
type.signature.properties.push({
key: getTSTypeWithResolvedTypes(
param
.get('parameters')
.get(0)
.get('typeAnnotation'),
typeParams,
),
value: getTSTypeWithRequirements(
param.get('typeAnnotation'),
typeParams,
),
});
}
});
return type;
}
function handleTSInterfaceDeclaration(path: NodePath): FlowElementsType {
// Interfaces are handled like references which would be documented separately,
// rather than inlined like type aliases.
return {
name: path.node.id.name,
};
}
function handleTSUnionType(
path: NodePath,
typeParams: ?TypeParameters,
): FlowElementsType {
return {
name: 'union',
raw: printValue(path),
elements: path
.get('types')
.map(subType => getTSTypeWithResolvedTypes(subType, typeParams)),
};
}
function handleTSIntersectionType(
path: NodePath,
typeParams: ?TypeParameters,
): FlowElementsType {
return {
name: 'intersection',
raw: printValue(path),
elements: path
.get('types')
.map(subType => getTSTypeWithResolvedTypes(subType, typeParams)),
};
}
function handleTSFunctionType(
path: NodePath,
typeParams: ?TypeParameters,
): FlowFunctionSignatureType {
const type: FlowFunctionSignatureType = {
name: 'signature',
type: 'function',
raw: printValue(path),
signature: {
arguments: [],
return: getTSTypeWithResolvedTypes(
path.get('typeAnnotation'),
typeParams,
),
},
};
path.get('parameters').each(param => {
const typeAnnotation = getTypeAnnotation(param);
let name = param.node.name || '';
if (param.node.type === 'RestElement') {
name = param.node.argument.name;
}
type.signature.arguments.push({
name,
type: typeAnnotation
? getTSTypeWithResolvedTypes(typeAnnotation, typeParams)
: null,
});
});
return type;
}
function handleTSTupleType(
path: NodePath,
typeParams: ?TypeParameters,
): FlowElementsType {
const type: FlowElementsType = {
name: 'tuple',
raw: printValue(path),
elements: [],
};
path.get('elementTypes').each(param => {
type.elements.push(getTSTypeWithResolvedTypes(param, typeParams));
});
return type;
}
function handleTSTypeQuery(
path: NodePath,
typeParams: ?TypeParameters,
): FlowTypeDescriptor {
const resolvedPath = resolveToValue(path.get('exprName'));
if (resolvedPath && resolvedPath.node.typeAnnotation) {
return getTSTypeWithResolvedTypes(
resolvedPath.get('typeAnnotation'),
typeParams,
);
}
return { name: path.node.exprName.name };
}
function handleTSTypeOperator(path: NodePath): FlowTypeDescriptor {
if (path.node.operator !== 'keyof') {
return null;
}
let value = path.get('typeAnnotation');
if (types.TSTypeQuery.check(value.node)) {
value = value.get('exprName');
} else if (value.node.id) {
value = value.get('id');
}
const resolvedPath = resolveToValue(value);
if (
resolvedPath &&
(types.ObjectExpression.check(resolvedPath.node) ||
types.TSTypeLiteral.check(resolvedPath.node))
) {
const keys = resolveObjectToNameArray(resolvedPath, true);
if (keys) {
return {
name: 'union',
raw: printValue(path),
elements: keys.map(key => ({ name: 'literal', value: key })),
};
}
}
}
let visitedTypes = {};
function getTSTypeWithResolvedTypes(
path: NodePath,
typeParams: ?TypeParameters,
): FlowTypeDescriptor {
if (types.TSTypeAnnotation.check(path.node)) {
path = path.get('typeAnnotation');
}
const node = path.node;
let type: ?FlowTypeDescriptor;
const isTypeAlias = types.TSTypeAliasDeclaration.check(path.parentPath.node);
// When we see a typealias mark it as visited so that the next
// call of this function does not run into an endless loop
if (isTypeAlias) {
if (visitedTypes[path.parentPath.node.id.name] === true) {
// if we are currently visiting this node then just return the name
// as we are starting to endless loop
return { name: path.parentPath.node.id.name };
} else if (typeof visitedTypes[path.parentPath.node.id.name] === 'object') {
// if we already resolved the type simple return it
return visitedTypes[path.parentPath.node.id.name];
}
// mark the type as visited
visitedTypes[path.parentPath.node.id.name] = true;
}
if (node.type in tsTypes) {
type = { name: tsTypes[node.type] };
} else if (types.TSLiteralType.check(node)) {
type = {
name: 'literal',
value: node.literal.raw || `${node.literal.value}`,
};
} else if (node.type in namedTypes) {
type = namedTypes[node.type](path, typeParams);
}
if (!type) {
type = { name: 'unknown' };
}
if (isTypeAlias) {
// mark the type as unvisited so that further calls can resolve the type again
visitedTypes[path.parentPath.node.id.name] = type;
}
return type;
}
/**
* Tries to identify the typescript type by inspecting the path for known
* typescript type names. This method doesn't check whether the found type is actually
* existing. It simply assumes that a match is always valid.
*
* If there is no match, "unknown" is returned.
*/
export default function getTSType(
path: NodePath,
typeParamMap: ?TypeParameters,
): FlowTypeDescriptor {
// Empty visited types before an after run
// Before: in case the detection threw and we rerun again
// After: cleanup memory after we are done here
visitedTypes = {};
const type = getTSTypeWithResolvedTypes(path, typeParamMap);
visitedTypes = {};
return type;
}