-
Notifications
You must be signed in to change notification settings - Fork 189
/
Type.ts
609 lines (530 loc) · 16.4 KB
/
Type.ts
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
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
import { errors, ObjectFlags, ts, TypeFlags, TypeFormatFlags } from "@ts-morph/common";
import { ProjectContext } from "../../ProjectContext";
import { getNotFoundErrorMessageForNameOrFindFunction, getSymbolByNameOrFindFunction } from "../../utils";
import { Node } from "../ast";
import { Signature, Symbol } from "../symbols";
import { TypeParameter } from "./TypeParameter";
export class Type<TType extends ts.Type = ts.Type> {
/** @internal */
readonly _context: ProjectContext;
/** @internal */
private readonly _compilerType: TType;
/**
* Gets the underlying compiler type.
*/
get compilerType() {
return this._compilerType;
}
/**
* Initializes a new instance of Type.
* @private
* @param context - Project context.
* @param type - Compiler type.
*/
constructor(context: ProjectContext, type: TType) {
this._context = context;
this._compilerType = type;
}
/**
* Gets the type text.
* @param enclosingNode - The enclosing node.
* @param typeFormatFlags - Format flags for the type text.
*/
getText(enclosingNode?: Node, typeFormatFlags?: TypeFormatFlags): string {
return this._context.typeChecker.getTypeText(this, enclosingNode, typeFormatFlags);
}
/**
* Gets the alias symbol if it exists.
*/
getAliasSymbol(): Symbol | undefined {
return this.compilerType.aliasSymbol == null ? undefined : this._context.compilerFactory.getSymbol(this.compilerType.aliasSymbol);
}
/**
* Gets the alias symbol if it exists, or throws.
*/
getAliasSymbolOrThrow(): Symbol {
return errors.throwIfNullOrUndefined(this.getAliasSymbol(), "Expected to find an alias symbol.");
}
/**
* Gets the alias type arguments.
*/
getAliasTypeArguments(): Type[] {
const aliasTypeArgs = this.compilerType.aliasTypeArguments || [];
return aliasTypeArgs.map(t => this._context.compilerFactory.getType(t));
}
/**
* Gets the apparent type.
*/
getApparentType(): Type {
return this._context.typeChecker.getApparentType(this);
}
/**
* Gets the array element type or throws if it doesn't exist (ex. for `T[]` it would be `T`).
*/
getArrayElementTypeOrThrow() {
return errors.throwIfNullOrUndefined(this.getArrayElementType(), "Expected to find an array element type.");
}
/**
* Gets the array element type or returns undefined if it doesn't exist (ex. for `T[]` it would be `T`).
*/
getArrayElementType() {
if (!this.isArray())
return undefined;
return this.getTypeArguments()[0];
}
/**
* Gets the base types.
*/
getBaseTypes() {
const baseTypes = this.compilerType.getBaseTypes() || [];
return baseTypes.map(t => this._context.compilerFactory.getType(t));
}
/**
* Gets the base type of a literal type.
*
* For example, for a number literal type it will return the number type.
*/
getBaseTypeOfLiteralType() {
return this._context.typeChecker.getBaseTypeOfLiteralType(this);
}
/**
* Gets the call signatures.
*/
getCallSignatures(): Signature[] {
return this.compilerType.getCallSignatures().map(s => this._context.compilerFactory.getSignature(s));
}
/**
* Gets the construct signatures.
*/
getConstructSignatures(): Signature[] {
return this.compilerType.getConstructSignatures().map(s => this._context.compilerFactory.getSignature(s));
}
/**
* Gets the constraint or throws if it doesn't exist.
*/
getConstraintOrThrow() {
return errors.throwIfNullOrUndefined(this.getConstraint(), "Expected to find a constraint.");
}
/**
* Gets the constraint or returns undefined if it doesn't exist.
*/
getConstraint() {
const constraint = this.compilerType.getConstraint();
return constraint == null ? undefined : this._context.compilerFactory.getType(constraint);
}
/**
* Gets the default type or throws if it doesn't exist.
*/
getDefaultOrThrow() {
return errors.throwIfNullOrUndefined(this.getDefault(), "Expected to find a default type.");
}
/**
* Gets the default type or returns undefined if it doesn't exist.
*/
getDefault() {
const defaultType = this.compilerType.getDefault();
return defaultType == null ? undefined : this._context.compilerFactory.getType(defaultType);
}
/**
* Gets the properties of the type.
*/
getProperties(): Symbol[] {
return this.compilerType.getProperties().map(s => this._context.compilerFactory.getSymbol(s));
}
/**
* Gets a property or throws if it doesn't exist.
* @param name - By a name.
*/
getPropertyOrThrow(name: string): Symbol;
/**
* Gets a property or throws if it doesn't exist.
* @param findFunction - Function for searching for a property.
*/
getPropertyOrThrow(findFunction: (declaration: Symbol) => boolean): Symbol;
/** @internal */
getPropertyOrThrow(nameOrFindFunction: string | ((declaration: Symbol) => boolean)): Symbol;
getPropertyOrThrow(nameOrFindFunction: string | ((declaration: Symbol) => boolean)): Symbol {
return errors.throwIfNullOrUndefined(
this.getProperty(nameOrFindFunction),
() => getNotFoundErrorMessageForNameOrFindFunction("symbol property", nameOrFindFunction),
);
}
/**
* Gets a property or returns undefined if it does not exist.
* @param name - By a name.
*/
getProperty(name: string): Symbol | undefined;
/**
* Gets a property or returns undefined if it does not exist.
* @param findFunction - Function for searching for a property.
*/
getProperty(findFunction: (declaration: Symbol) => boolean): Symbol | undefined;
/** @internal */
getProperty(nameOrFindFunction: string | ((declaration: Symbol) => boolean)): Symbol | undefined;
getProperty(nameOrFindFunction: string | ((declaration: Symbol) => boolean)): Symbol | undefined {
return getSymbolByNameOrFindFunction(this.getProperties(), nameOrFindFunction);
}
/**
* Gets the apparent properties of the type.
*/
getApparentProperties(): Symbol[] {
return this.compilerType.getApparentProperties().map(s => this._context.compilerFactory.getSymbol(s));
}
/**
* Gets an apparent property.
* @param name - By a name.
* @param findFunction - Function for searching for an apparent property.
*/
getApparentProperty(name: string): Symbol | undefined;
getApparentProperty(findFunction: (declaration: Symbol) => boolean): Symbol | undefined;
getApparentProperty(nameOrFindFunction: string | ((declaration: Symbol) => boolean)): Symbol | undefined {
return getSymbolByNameOrFindFunction(this.getApparentProperties(), nameOrFindFunction);
}
/**
* Gets if the type is possibly null or undefined.
*/
isNullable() {
return this.getUnionTypes().some(t => t.isNull() || t.isUndefined());
}
/**
* Gets the non-nullable type.
*/
getNonNullableType(): Type {
return this._context.compilerFactory.getType(this.compilerType.getNonNullableType());
}
/**
* Gets the number index type.
*/
getNumberIndexType(): Type | undefined {
const numberIndexType = this.compilerType.getNumberIndexType();
return numberIndexType == null ? undefined : this._context.compilerFactory.getType(numberIndexType);
}
/**
* Gets the string index type.
*/
getStringIndexType(): Type | undefined {
const stringIndexType = this.compilerType.getStringIndexType();
return stringIndexType == null ? undefined : this._context.compilerFactory.getType(stringIndexType);
}
/**
* Returns the generic type when the type is a type reference, returns itself when it's
* already a generic type, or otherwise returns undefined.
*
* For example:
*
* - Given type reference `Promise<string>` returns `Promise<T>`.
* - Given generic type `Promise<T>` returns the same `Promise<T>`.
* - Given `string` returns `undefined`.
*/
getTargetType(): Type<ts.GenericType> | undefined {
const targetType = (this.compilerType as any as ts.TypeReference).target || undefined;
return targetType == null ? undefined : this._context.compilerFactory.getType(targetType);
}
/**
* Returns the generic type when the type is a type reference, returns itself when it's
* already a generic type, or otherwise throws an error.
*
* For example:
*
* - Given type reference `Promise<string>` returns `Promise<T>`.
* - Given generic type `Promise<T>` returns the same `Promise<T>`.
* - Given `string` throws an error.
*/
getTargetTypeOrThrow(): Type<ts.GenericType> {
return errors.throwIfNullOrUndefined(this.getTargetType(), "Expected to find the target type.");
}
/**
* Gets type arguments.
*/
getTypeArguments(): Type[] {
return this._context.typeChecker.getTypeArguments(this);
}
/**
* Gets the individual element types of the tuple.
*/
getTupleElements(): Type[] {
return this.isTuple() ? this.getTypeArguments() : [];
}
/**
* Gets the union types (ex. for `T | U` it returns the array `[T, U]`).
*/
getUnionTypes(): Type[] {
if (!this.isUnion())
return [];
return (this.compilerType as any as ts.UnionType).types.map(t => this._context.compilerFactory.getType(t));
}
/**
* Gets the intersection types (ex. for `T & U` it returns the array `[T, U]`).
*/
getIntersectionTypes(): Type[] {
if (!this.isIntersection())
return [];
return (this.compilerType as any as ts.IntersectionType).types.map(t => this._context.compilerFactory.getType(t));
}
/**
* Gets the value of a literal or returns undefined if this is not a literal type.
*/
getLiteralValue() {
return (this.compilerType as any as ts.LiteralType | undefined)?.value;
}
/**
* Gets the value of the literal or throws if this is not a literal type.
*/
getLiteralValueOrThrow() {
return errors.throwIfNullOrUndefined(this.getLiteralValue(), "Type was not a literal type.");
}
/**
* Gets the fresh type of the literal or returns undefined if this is not a literal type.
*
* Note: I have no idea what this means. Please help contribute to these js docs if you know.
*/
getLiteralFreshType() {
const type = (this.compilerType as any as ts.LiteralType | undefined)?.freshType;
return type == null ? undefined : this._context.compilerFactory.getType(type);
}
/**
* Gets the fresh type of the literal or throws if this is not a literal type.
*
* Note: I have no idea what this means. Please help contribute to these js docs if you know.
*/
getLiteralFreshTypeOrThrow() {
return errors.throwIfNullOrUndefined(this.getLiteralFreshType(), "Type was not a literal type.");
}
/**
* Gets the regular type of the literal or returns undefined if this is not a literal type.
*
* Note: I have no idea what this means. Please help contribute to these js docs if you know.
*/
getLiteralRegularType() {
const type = (this.compilerType as any as ts.LiteralType | undefined)?.regularType;
return type == null ? undefined : this._context.compilerFactory.getType(type);
}
/**
* Gets the regular type of the literal or throws if this is not a literal type.
*
* Note: I have no idea what this means. Please help contribute to these js docs if you know.
*/
getLiteralRegularTypeOrThrow() {
return errors.throwIfNullOrUndefined(this.getLiteralRegularType(), "Type was not a literal type.");
}
/**
* Gets the symbol of the type.
*/
getSymbol(): Symbol | undefined {
const tsSymbol = this.compilerType.getSymbol();
return tsSymbol == null ? undefined : this._context.compilerFactory.getSymbol(tsSymbol);
}
/**
* Gets the symbol of the type or throws.
*/
getSymbolOrThrow(): Symbol {
return errors.throwIfNullOrUndefined(this.getSymbol(), "Expected to find a symbol.");
}
/**
* Gets if this is an anonymous type.
*/
isAnonymous() {
return this._hasObjectFlag(ObjectFlags.Anonymous);
}
/**
* Gets if this is an any type.
*/
isAny() {
return this._hasTypeFlag(TypeFlags.Any);
}
/**
* Gets if this is a never type.
*/
isNever() {
return this._hasTypeFlag(TypeFlags.Never);
}
/**
* Gets if this is an array type.
*/
isArray() {
const symbol = this.getSymbol();
if (symbol == null)
return false;
// this is not bulletproof and should be improved
return (symbol.getName() === "Array" || symbol.getName() === "ReadonlyArray") && this.getTypeArguments().length === 1;
}
/**
* Gets if this is a readonly array type.
*/
isReadonlyArray() {
const symbol = this.getSymbol();
if (symbol == null)
return false;
// this is not bulletproof and should be improved
return symbol.getName() === "ReadonlyArray" && this.getTypeArguments().length === 1;
}
/**
* Gets if this is a template literal type.
*/
isTemplateLiteral() {
return this._hasTypeFlag(TypeFlags.TemplateLiteral);
}
/**
* Gets if this is a boolean type.
*/
isBoolean() {
return this._hasTypeFlag(TypeFlags.Boolean);
}
/**
* Gets if this is a string type.
*/
isString() {
return this._hasTypeFlag(TypeFlags.String);
}
/**
* Gets if this is a number type.
*/
isNumber() {
return this._hasTypeFlag(TypeFlags.Number);
}
/**
* Gets if this is a literal type.
*/
isLiteral() {
// todo: remove this when https://github.com/Microsoft/TypeScript/issues/26075 is fixed
const isBooleanLiteralForTs3_0 = this.isBooleanLiteral();
return this.compilerType.isLiteral() || isBooleanLiteralForTs3_0;
}
/**
* Gets if this is a boolean literal type.
*/
isBooleanLiteral() {
return this._hasTypeFlag(TypeFlags.BooleanLiteral);
}
/**
* Gets if this is an enum literal type.
*/
isEnumLiteral() {
return this._hasTypeFlag(TypeFlags.EnumLiteral) && !this.isUnion();
}
/**
* Gets if this is a number literal type.
*/
isNumberLiteral() {
return this._hasTypeFlag(TypeFlags.NumberLiteral);
}
/**
* Gets if this is a string literal type.
*/
isStringLiteral() {
return this.compilerType.isStringLiteral();
}
/**
* Gets if this is a class type.
*/
isClass() {
return this.compilerType.isClass();
}
/**
* Gets if this is a class or interface type.
*/
isClassOrInterface() {
return this.compilerType.isClassOrInterface();
}
/**
* Gets if this is an enum type.
*/
isEnum() {
const hasEnumFlag = this._hasTypeFlag(TypeFlags.Enum);
if (hasEnumFlag)
return true;
if (this.isEnumLiteral() && !this.isUnion())
return false;
const symbol = this.getSymbol();
if (symbol == null)
return false;
const valueDeclaration = symbol.getValueDeclaration();
return valueDeclaration != null && Node.isEnumDeclaration(valueDeclaration);
}
/**
* Gets if this is an interface type.
*/
isInterface() {
return this._hasObjectFlag(ObjectFlags.Interface);
}
/**
* Gets if this is an object type.
*/
isObject() {
return this._hasTypeFlag(TypeFlags.Object);
}
/**
* Gets if this is a type parameter.
*/
isTypeParameter(): this is TypeParameter {
return this.compilerType.isTypeParameter();
}
/**
* Gets if this is a tuple type.
*/
isTuple() {
const targetType = this.getTargetType();
if (targetType == null)
return false;
return targetType._hasObjectFlag(ObjectFlags.Tuple);
}
/**
* Gets if this is a union type.
*/
isUnion() {
return this.compilerType.isUnion();
}
/**
* Gets if this is an intersection type.
*/
isIntersection() {
return this.compilerType.isIntersection();
}
/**
* Gets if this is a union or intersection type.
*/
isUnionOrIntersection() {
return this.compilerType.isUnionOrIntersection();
}
/**
* Gets if this is the unknown type.
*/
isUnknown() {
return this._hasTypeFlag(TypeFlags.Unknown);
}
/**
* Gets if this is the null type.
*/
isNull() {
return this._hasTypeFlag(TypeFlags.Null);
}
/**
* Gets if this is the undefined type.
*/
isUndefined() {
return this._hasTypeFlag(TypeFlags.Undefined);
}
/**
* Gets the type flags.
*/
getFlags(): TypeFlags {
return this.compilerType.flags;
}
/**
* Gets the object flags.
* @remarks Returns 0 for a non-object type.
*/
getObjectFlags() {
if (!this.isObject())
return 0;
return (this.compilerType as any as ts.ObjectType).objectFlags || 0;
}
/** @internal */
private _hasTypeFlag(flag: TypeFlags) {
return (this.compilerType.flags & flag) === flag;
}
/** @internal */
private _hasObjectFlag(flag: ObjectFlags) {
return (this.getObjectFlags() & flag) === flag;
}
}