/
types.ts
1054 lines (960 loc) · 34.2 KB
/
types.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
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import * as assert from "assert";
import * as ts from "typescript";
import {
ArrayType,
ConditionalType,
DeclarationReflection,
IndexedAccessType,
InferredType,
IntersectionType,
IntrinsicType,
NamedTupleMember,
PredicateType,
QueryType,
ReferenceType,
ReflectionKind,
ReflectionType,
LiteralType,
TupleType,
Type,
TypeOperatorType,
UnionType,
UnknownType,
MappedType,
SignatureReflection,
ReflectionFlag,
} from "../models";
import { OptionalType } from "../models/types/optional";
import { RestType } from "../models/types/rest";
import { TemplateLiteralType } from "../models/types/template-literal";
import { zip } from "../utils/array";
import { Context } from "./context";
import { ConverterEvents } from "./converter-events";
import { convertIndexSignature } from "./factories/index-signature";
import {
convertParameterNodes,
convertTypeParameterNodes,
createSignature,
} from "./factories/signature";
import { convertSymbol } from "./symbols";
import { removeUndefined } from "./utils/reflections";
export interface TypeConverter<
TNode extends ts.TypeNode = ts.TypeNode,
TType extends ts.Type = ts.Type
> {
kind: TNode["kind"][];
// getTypeAtLocation is expensive, so don't pass the type here.
convert(context: Context, node: TNode): Type;
// We use typeToTypeNode to figure out what method to call in the first place,
// so we have a non-type-checkable node here, necessary for some converters.
convertType(context: Context, type: TType, node: TNode): Type;
}
const converters = new Map<ts.SyntaxKind, TypeConverter>();
export function loadConverters() {
if (converters.size) return;
for (const actor of [
arrayConverter,
conditionalConverter,
constructorConverter,
exprWithTypeArgsConverter,
functionTypeConverter,
importType,
indexedAccessConverter,
inferredConverter,
intersectionConverter,
jsDocVariadicTypeConverter,
keywordConverter,
optionalConverter,
parensConverter,
predicateConverter,
queryConverter,
typeLiteralConverter,
referenceConverter,
restConverter,
namedTupleMemberConverter,
mappedConverter,
ts3LiteralBooleanConverter,
ts3LiteralNullConverter,
ts3LiteralThisConverter,
literalTypeConverter,
templateLiteralConverter,
thisConverter,
tupleConverter,
typeOperatorConverter,
unionConverter,
// Only used if skipLibCheck: true
jsDocNullableTypeConverter,
jsDocNonNullableTypeConverter,
]) {
for (const key of actor.kind) {
if (key === undefined) {
// Might happen if running on an older TS version.
continue;
}
assert(!converters.has(key));
converters.set(key, actor);
}
}
}
// This ought not be necessary, but we need some way to discover recursively
// typed symbols which do not have type nodes. See the `recursive` symbol in the variables test.
const seenTypeSymbols = new Set<ts.Symbol>();
export function convertType(
context: Context,
typeOrNode: ts.Type | ts.TypeNode | undefined
): Type {
if (!typeOrNode) {
return new IntrinsicType("any");
}
loadConverters();
if ("kind" in typeOrNode) {
const converter = converters.get(typeOrNode.kind);
if (converter) {
return converter.convert(context, typeOrNode);
}
return requestBugReport(context, typeOrNode);
}
// IgnoreErrors is important, without it, we can't assert that we will get a node.
const node = context.checker.typeToTypeNode(
typeOrNode,
void 0,
ts.NodeBuilderFlags.IgnoreErrors
);
assert(node); // According to the TS source of typeToString, this is a bug if it does not hold.
const symbol = typeOrNode.getSymbol();
if (symbol) {
if (
node.kind !== ts.SyntaxKind.TypeReference &&
node.kind !== ts.SyntaxKind.ArrayType &&
seenTypeSymbols.has(symbol)
) {
const typeString = context.checker.typeToString(typeOrNode);
context.logger.verbose(
`Refusing to recurse when converting type: ${typeString}`
);
return new UnknownType(typeString);
}
seenTypeSymbols.add(symbol);
}
const converter = converters.get(node.kind);
if (converter) {
const result = converter.convertType(context, typeOrNode, node);
if (symbol) seenTypeSymbols.delete(symbol);
return result;
}
return requestBugReport(context, typeOrNode);
}
const arrayConverter: TypeConverter<ts.ArrayTypeNode, ts.TypeReference> = {
kind: [ts.SyntaxKind.ArrayType],
convert(context, node) {
return new ArrayType(convertType(context, node.elementType));
},
convertType(context, type) {
const params = context.checker.getTypeArguments(type);
// This is *almost* always true... except for when this type is in the constraint of a type parameter see GH#1408
// assert(params.length === 1);
assert(params.length > 0);
return new ArrayType(convertType(context, params[0]));
},
};
const conditionalConverter: TypeConverter<
ts.ConditionalTypeNode,
ts.ConditionalType
> = {
kind: [ts.SyntaxKind.ConditionalType],
convert(context, node) {
return new ConditionalType(
convertType(context, node.checkType),
convertType(context, node.extendsType),
convertType(context, node.trueType),
convertType(context, node.falseType)
);
},
convertType(context, type) {
return new ConditionalType(
convertType(context, type.checkType),
convertType(context, type.extendsType),
convertType(context, type.resolvedTrueType),
convertType(context, type.resolvedFalseType)
);
},
};
const constructorConverter: TypeConverter<ts.ConstructorTypeNode, ts.Type> = {
kind: [ts.SyntaxKind.ConstructorType],
convert(context, node) {
const symbol = context.getSymbolAtLocation(node) ?? node.symbol;
const type = context.getTypeAtLocation(node);
if (!symbol || !type) {
return new IntrinsicType("Function");
}
const reflection = new DeclarationReflection(
"__type",
ReflectionKind.Constructor,
context.scope
);
const rc = context.withScope(reflection);
rc.setConvertingTypeNode();
context.registerReflection(reflection, symbol);
context.trigger(ConverterEvents.CREATE_DECLARATION, reflection, node);
const signature = new SignatureReflection(
"__type",
ReflectionKind.ConstructorSignature,
reflection
);
// This is unfortunate... but seems the obvious place to put this with the current
// architecture. Ideally, this would be a property on a "ConstructorType"... but that
// needs to wait until TypeDoc 0.22 when making other breaking changes.
if (
node.modifiers?.some(
(m) => m.kind === ts.SyntaxKind.AbstractKeyword
)
) {
signature.setFlag(ReflectionFlag.Abstract);
}
context.registerReflection(signature, void 0);
const signatureCtx = rc.withScope(signature);
reflection.signatures = [signature];
signature.type = convertType(signatureCtx, node.type);
signature.parameters = convertParameterNodes(
signatureCtx,
signature,
node.parameters
);
signature.typeParameters = convertTypeParameterNodes(
signatureCtx,
node.typeParameters
);
return new ReflectionType(reflection);
},
convertType(context, type) {
if (!type.symbol) {
return new IntrinsicType("Function");
}
const reflection = new DeclarationReflection(
"__type",
ReflectionKind.Constructor,
context.scope
);
context.registerReflection(reflection, type.symbol);
context.trigger(ConverterEvents.CREATE_DECLARATION, reflection);
createSignature(
context.withScope(reflection),
ReflectionKind.ConstructorSignature,
type.getConstructSignatures()[0]
);
return new ReflectionType(reflection);
},
};
const exprWithTypeArgsConverter: TypeConverter<
ts.ExpressionWithTypeArguments,
ts.Type
> = {
kind: [ts.SyntaxKind.ExpressionWithTypeArguments],
convert(context, node) {
const targetSymbol = context.getSymbolAtLocation(node.expression);
// Mixins... we might not have a symbol here.
if (!targetSymbol) {
return convertType(
context,
context.checker.getTypeAtLocation(node)
);
}
const parameters =
node.typeArguments?.map((type) => convertType(context, type)) ?? [];
const ref = new ReferenceType(
targetSymbol.name,
context.resolveAliasedSymbol(targetSymbol),
context.project
);
ref.typeArguments = parameters;
return ref;
},
convertType: requestBugReport,
};
const functionTypeConverter: TypeConverter<ts.FunctionTypeNode, ts.Type> = {
kind: [ts.SyntaxKind.FunctionType],
convert(context, node) {
const symbol = context.getSymbolAtLocation(node) ?? node.symbol;
const type = context.getTypeAtLocation(node);
if (!symbol || !type) {
return new IntrinsicType("Function");
}
const reflection = new DeclarationReflection(
"__type",
ReflectionKind.TypeLiteral,
context.scope
);
const rc = context.withScope(reflection);
context.registerReflection(reflection, symbol);
context.trigger(ConverterEvents.CREATE_DECLARATION, reflection, node);
const signature = new SignatureReflection(
"__type",
ReflectionKind.CallSignature,
reflection
);
context.registerReflection(signature, void 0);
const signatureCtx = rc.withScope(signature);
reflection.signatures = [signature];
signature.type = convertType(signatureCtx, node.type);
signature.parameters = convertParameterNodes(
signatureCtx,
signature,
node.parameters
);
signature.typeParameters = convertTypeParameterNodes(
signatureCtx,
node.typeParameters
);
return new ReflectionType(reflection);
},
convertType(context, type) {
if (!type.symbol) {
return new IntrinsicType("Function");
}
const reflection = new DeclarationReflection(
"__type",
ReflectionKind.TypeLiteral,
context.scope
);
context.registerReflection(reflection, type.symbol);
context.trigger(ConverterEvents.CREATE_DECLARATION, reflection);
createSignature(
context.withScope(reflection),
ReflectionKind.CallSignature,
type.getCallSignatures()[0]
);
return new ReflectionType(reflection);
},
};
const importType: TypeConverter<ts.ImportTypeNode> = {
kind: [ts.SyntaxKind.ImportType],
convert(context, node) {
const name = node.qualifier?.getText() ?? "__module";
const symbol = context.checker.getSymbolAtLocation(node);
assert(symbol, "Missing symbol when converting import type node");
return new ReferenceType(name, symbol, context.project);
},
convertType(context, type) {
const symbol = type.getSymbol();
assert(symbol, "Missing symbol when converting import type"); // Should be a compiler error
return new ReferenceType("__module", symbol, context.project);
},
};
const indexedAccessConverter: TypeConverter<
ts.IndexedAccessTypeNode,
ts.IndexedAccessType
> = {
kind: [ts.SyntaxKind.IndexedAccessType],
convert(context, node) {
return new IndexedAccessType(
convertType(context, node.objectType),
convertType(context, node.indexType)
);
},
convertType(context, type) {
return new IndexedAccessType(
convertType(context, type.objectType),
convertType(context, type.indexType)
);
},
};
const inferredConverter: TypeConverter<ts.InferTypeNode> = {
kind: [ts.SyntaxKind.InferType],
convert(_context, node) {
return new InferredType(node.typeParameter.getText());
},
convertType(_context, type) {
return new InferredType(type.symbol.name);
},
};
const intersectionConverter: TypeConverter<
ts.IntersectionTypeNode,
ts.IntersectionType
> = {
kind: [ts.SyntaxKind.IntersectionType],
convert(context, node) {
return new IntersectionType(
node.types.map((type) => convertType(context, type))
);
},
convertType(context, type) {
return new IntersectionType(
type.types.map((type) => convertType(context, type))
);
},
};
const jsDocVariadicTypeConverter: TypeConverter<ts.JSDocVariadicType> = {
kind: [ts.SyntaxKind.JSDocVariadicType],
convert(context, node) {
return new ArrayType(convertType(context, node.type));
},
// Should just be an ArrayType
convertType: requestBugReport,
};
const keywordNames = {
[ts.SyntaxKind.AnyKeyword]: "any",
[ts.SyntaxKind.BigIntKeyword]: "bigint",
[ts.SyntaxKind.BooleanKeyword]: "boolean",
[ts.SyntaxKind.NeverKeyword]: "never",
[ts.SyntaxKind.NumberKeyword]: "number",
[ts.SyntaxKind.ObjectKeyword]: "object",
[ts.SyntaxKind.StringKeyword]: "string",
[ts.SyntaxKind.SymbolKeyword]: "symbol",
[ts.SyntaxKind.UndefinedKeyword]: "undefined",
[ts.SyntaxKind.UnknownKeyword]: "unknown",
[ts.SyntaxKind.VoidKeyword]: "void",
[ts.SyntaxKind.IntrinsicKeyword]: "intrinsic",
};
const keywordConverter: TypeConverter<ts.KeywordTypeNode> = {
kind: [
ts.SyntaxKind.AnyKeyword,
ts.SyntaxKind.BigIntKeyword,
ts.SyntaxKind.BooleanKeyword,
ts.SyntaxKind.NeverKeyword,
ts.SyntaxKind.NumberKeyword,
ts.SyntaxKind.ObjectKeyword,
ts.SyntaxKind.StringKeyword,
ts.SyntaxKind.SymbolKeyword,
ts.SyntaxKind.UndefinedKeyword,
ts.SyntaxKind.UnknownKeyword,
ts.SyntaxKind.VoidKeyword,
],
convert(_context, node) {
return new IntrinsicType(keywordNames[node.kind]);
},
convertType(_context, _type, node) {
return new IntrinsicType(keywordNames[node.kind]);
},
};
const optionalConverter: TypeConverter<ts.OptionalTypeNode> = {
kind: [ts.SyntaxKind.OptionalType],
convert(context, node) {
return new OptionalType(
removeUndefined(convertType(context, node.type))
);
},
// Handled by the tuple converter
convertType: requestBugReport,
};
const parensConverter: TypeConverter<ts.ParenthesizedTypeNode> = {
kind: [ts.SyntaxKind.ParenthesizedType],
convert(context, node) {
return convertType(context, node.type);
},
// TS strips these out too... shouldn't run into this.
convertType: requestBugReport,
};
const predicateConverter: TypeConverter<ts.TypePredicateNode, ts.Type> = {
kind: [ts.SyntaxKind.TypePredicate],
convert(context, node) {
const name = ts.isThisTypeNode(node.parameterName)
? "this"
: node.parameterName.getText();
const asserts = !!node.assertsModifier;
const targetType = node.type ? convertType(context, node.type) : void 0;
return new PredicateType(name, asserts, targetType);
},
// Never inferred by TS 4.0, could potentially change in a future TS version.
convertType: requestBugReport,
};
// This is a horrible thing... we're going to want to split this into converters
// for different types at some point.
const typeLiteralConverter: TypeConverter<ts.TypeLiteralNode> = {
kind: [ts.SyntaxKind.TypeLiteral],
convert(context, node) {
const symbol = context.getSymbolAtLocation(node) ?? node.symbol;
const type = context.getTypeAtLocation(node);
if (!symbol || !type) {
return new IntrinsicType("Object");
}
const reflection = new DeclarationReflection(
"__type",
ReflectionKind.TypeLiteral,
context.scope
);
const rc = context.withScope(reflection);
rc.setConvertingTypeNode();
context.registerReflection(reflection, symbol);
context.trigger(ConverterEvents.CREATE_DECLARATION, reflection, node);
for (const prop of context.checker.getPropertiesOfType(type)) {
convertSymbol(rc, prop);
}
for (const signature of type.getCallSignatures()) {
createSignature(rc, ReflectionKind.CallSignature, signature);
}
convertIndexSignature(rc, symbol);
return new ReflectionType(reflection);
},
convertType(context, type) {
if (!type.symbol) {
return new IntrinsicType("Object");
}
const reflection = new DeclarationReflection(
"__type",
ReflectionKind.TypeLiteral,
context.scope
);
context.registerReflection(reflection, type.symbol);
context.trigger(ConverterEvents.CREATE_DECLARATION, reflection);
for (const prop of context.checker.getPropertiesOfType(type)) {
convertSymbol(context.withScope(reflection), prop);
}
for (const signature of type.getCallSignatures()) {
createSignature(
context.withScope(reflection),
ReflectionKind.CallSignature,
signature
);
}
convertIndexSignature(context.withScope(reflection), type.symbol);
return new ReflectionType(reflection);
},
};
const queryConverter: TypeConverter<ts.TypeQueryNode> = {
kind: [ts.SyntaxKind.TypeQuery],
convert(context, node) {
const querySymbol = context.expectSymbolAtLocation(node.exprName);
return new QueryType(
new ReferenceType(
node.exprName.getText(),
context.resolveAliasedSymbol(querySymbol),
context.project
)
);
},
convertType(context, type) {
const symbol = type.getSymbol();
assert(
symbol,
`Query type failed to get a symbol for: ${context.checker.typeToString(
type
)}. This is a bug.`
);
return new QueryType(
new ReferenceType(
symbol.name,
context.resolveAliasedSymbol(symbol),
context.project
)
);
},
};
const referenceConverter: TypeConverter<
ts.TypeReferenceNode,
ts.TypeReference
> = {
kind: [ts.SyntaxKind.TypeReference],
convert(context, node) {
const isArray =
context.checker.typeToTypeNode(
context.checker.getTypeAtLocation(node.typeName),
void 0,
ts.NodeBuilderFlags.IgnoreErrors
)?.kind === ts.SyntaxKind.ArrayType;
if (isArray) {
return new ArrayType(convertType(context, node.typeArguments?.[0]));
}
const symbol = context.expectSymbolAtLocation(node.typeName);
const name = node.typeName.getText();
const type = new ReferenceType(
name,
context.resolveAliasedSymbol(symbol),
context.project
);
type.typeArguments = node.typeArguments?.map((type) =>
convertType(context, type)
);
return type;
},
convertType(context, type) {
const symbol = type.aliasSymbol ?? type.getSymbol();
if (!symbol) {
// This happens when we get a reference to a type parameter
// created within a mapped type, `K` in: `{ [K in T]: string }`
return ReferenceType.createBrokenReference(
context.checker.typeToString(type),
context.project
);
}
const ref = new ReferenceType(
symbol.name,
context.resolveAliasedSymbol(symbol),
context.project
);
ref.typeArguments = (type.aliasSymbol
? type.aliasTypeArguments
: type.typeArguments
)?.map((ref) => convertType(context, ref));
return ref;
},
};
const restConverter: TypeConverter<ts.RestTypeNode> = {
kind: [ts.SyntaxKind.RestType],
convert(context, node) {
return new RestType(convertType(context, node.type));
},
// This is handled in the tuple converter
convertType: requestBugReport,
};
const namedTupleMemberConverter: TypeConverter<ts.NamedTupleMember> = {
kind: [ts.SyntaxKind.NamedTupleMember],
convert(context, node) {
const innerType = convertType(context, node.type);
return new NamedTupleMember(
node.name.getText(),
!!node.questionToken,
innerType
);
},
// This ought to be impossible.
convertType: requestBugReport,
};
// { -readonly [K in string]-?: number}
// ^ readonlyToken
// ^ typeParameter
// ^^^^^^ typeParameter.constraint
// ^ questionToken
// ^^^^^^ type
const mappedConverter: TypeConverter<
ts.MappedTypeNode,
ts.Type & {
// Beware! Internal TS API here.
templateType: ts.Type;
typeParameter: ts.TypeParameter;
constraintType: ts.Type;
nameType?: ts.Type;
}
> = {
kind: [ts.SyntaxKind.MappedType],
convert(context, node) {
const optionalModifier = kindToModifier(node.questionToken?.kind);
const templateType = convertType(context, node.type);
return new MappedType(
node.typeParameter.name.text,
convertType(context, node.typeParameter.constraint),
optionalModifier === "+"
? removeUndefined(templateType)
: templateType,
kindToModifier(node.readonlyToken?.kind),
optionalModifier,
node.nameType ? convertType(context, node.nameType) : void 0
);
},
convertType(context, type, node) {
// This can happen if a generic function does not have a return type annotated.
const optionalModifier = kindToModifier(node.questionToken?.kind);
const templateType = convertType(context, type.templateType);
return new MappedType(
type.typeParameter.symbol?.name,
convertType(context, type.typeParameter.getConstraint()),
optionalModifier === "+"
? removeUndefined(templateType)
: templateType,
kindToModifier(node.readonlyToken?.kind),
optionalModifier,
type.nameType ? convertType(context, type.nameType) : void 0
);
},
};
const ts3LiteralBooleanConverter: TypeConverter<ts.TypeNode, ts.Type> = {
kind: [ts.SyntaxKind.TrueKeyword, ts.SyntaxKind.FalseKeyword],
convert(_context, node) {
return new LiteralType(node.kind === ts.SyntaxKind.TrueKeyword);
},
convertType(_context, _type, node) {
return new LiteralType(node.kind === ts.SyntaxKind.TrueKeyword);
},
};
const ts3LiteralNullConverter: TypeConverter<ts.TypeNode, ts.Type> = {
kind: [ts.SyntaxKind.NullKeyword],
convert() {
return new LiteralType(null);
},
convertType() {
return new LiteralType(null);
},
};
const ts3LiteralThisConverter: TypeConverter<ts.TypeNode, ts.Type> = {
kind: [ts.SyntaxKind.ThisKeyword],
convert() {
return new IntrinsicType("this");
},
convertType() {
return new IntrinsicType("this");
},
};
const literalTypeConverter: TypeConverter<
ts.LiteralTypeNode,
ts.LiteralType
> = {
kind: [ts.SyntaxKind.LiteralType],
convert(context, node) {
switch (node.literal.kind) {
case ts.SyntaxKind.TrueKeyword:
case ts.SyntaxKind.FalseKeyword:
return new LiteralType(
node.literal.kind === ts.SyntaxKind.TrueKeyword
);
case ts.SyntaxKind.StringLiteral:
return new LiteralType(node.literal.text);
case ts.SyntaxKind.NumericLiteral:
return new LiteralType(Number(node.literal.text));
case ts.SyntaxKind.NullKeyword:
return new LiteralType(null);
case ts.SyntaxKind.PrefixUnaryExpression: {
const operand = (node.literal as ts.PrefixUnaryExpression)
.operand;
switch (operand.kind) {
case ts.SyntaxKind.NumericLiteral:
return new LiteralType(Number(node.literal.getText()));
case ts.SyntaxKind.BigIntLiteral:
return new LiteralType(
BigInt(node.literal.getText().replace("n", ""))
);
default:
return requestBugReport(context, node.literal);
}
}
case ts.SyntaxKind.BigIntLiteral:
return new LiteralType(
BigInt(node.literal.getText().replace("n", ""))
);
case ts.SyntaxKind.NoSubstitutionTemplateLiteral:
return new LiteralType(node.literal.text);
}
return requestBugReport(context, node.literal);
},
convertType(_context, type, node) {
switch (node.literal.kind) {
case ts.SyntaxKind.StringLiteral:
return new LiteralType(node.literal.text);
case ts.SyntaxKind.NumericLiteral:
return new LiteralType(+node.literal.text);
case ts.SyntaxKind.TrueKeyword:
case ts.SyntaxKind.FalseKeyword:
return new LiteralType(
node.literal.kind === ts.SyntaxKind.TrueKeyword
);
case ts.SyntaxKind.NullKeyword:
return new LiteralType(null);
}
if (typeof type.value === "object") {
return new LiteralType(
BigInt(
`${type.value.negative ? "-" : ""}${type.value.base10Value}`
)
);
}
return new LiteralType(type.value);
},
};
const templateLiteralConverter: TypeConverter<
ts.TemplateLiteralTypeNode,
ts.TemplateLiteralType
> = {
kind: [ts.SyntaxKind.TemplateLiteralType],
convert(context, node) {
return new TemplateLiteralType(
node.head.text,
node.templateSpans.map((span) => {
return [convertType(context, span.type), span.literal.text];
})
);
},
convertType(context, type) {
assert(type.texts.length === type.types.length + 1);
const parts: [Type, string][] = [];
for (const [a, b] of zip(type.types, type.texts.slice(1))) {
parts.push([convertType(context, a), b]);
}
return new TemplateLiteralType(type.texts[0], parts);
},
};
const thisConverter: TypeConverter<ts.ThisTypeNode> = {
kind: [ts.SyntaxKind.ThisType],
convert() {
return new IntrinsicType("this");
},
convertType() {
return new IntrinsicType("this");
},
};
const tupleConverter: TypeConverter<ts.TupleTypeNode, ts.TupleTypeReference> = {
kind: [ts.SyntaxKind.TupleType],
convert(context, node) {
const elements = node.elements.map((node) =>
convertType(context, node)
);
return new TupleType(elements);
},
convertType(context, type) {
const types = type.typeArguments?.slice(0, type.target.fixedLength);
let elements = types?.map((type) => convertType(context, type));
if (type.target.labeledElementDeclarations) {
const namedDeclarations = type.target.labeledElementDeclarations;
elements = elements?.map(
(el, i) =>
new NamedTupleMember(
namedDeclarations[i].name.getText(),
!!namedDeclarations[i].questionToken,
removeUndefined(el)
)
);
}
elements = elements?.map((el, i) => {
if (type.target.elementFlags[i] & ts.ElementFlags.Variable) {
// In the node case, we don't need to add the wrapping Array type... but we do here.
if (el instanceof NamedTupleMember) {
return new RestType(
new NamedTupleMember(
el.name,
el.isOptional,
new ArrayType(el.element)
)
);
}
return new RestType(new ArrayType(el));
}
if (
type.target.elementFlags[i] & ts.ElementFlags.Optional &&
!(el instanceof NamedTupleMember)
) {
return new OptionalType(removeUndefined(el));
}
return el;
});
return new TupleType(elements ?? []);
},
};
const supportedOperatorNames = {
[ts.SyntaxKind.KeyOfKeyword]: "keyof",
[ts.SyntaxKind.UniqueKeyword]: "unique",
[ts.SyntaxKind.ReadonlyKeyword]: "readonly",
} as const;
const typeOperatorConverter: TypeConverter<ts.TypeOperatorNode> = {
kind: [ts.SyntaxKind.TypeOperator],
convert(context, node) {
return new TypeOperatorType(
convertType(context, node.type),
supportedOperatorNames[node.operator]
);
},
convertType(context, type, node) {
// readonly is only valid on array and tuple literal types.
if (node.operator === ts.SyntaxKind.ReadonlyKeyword) {
const resolved = resolveReference(type);
assert(isObjectType(resolved));
const args = context.checker
.getTypeArguments(type as ts.TypeReference)
.map((type) => convertType(context, type));
const inner =
resolved.objectFlags & ts.ObjectFlags.Tuple
? new TupleType(args)
: new ArrayType(args[0]);
return new TypeOperatorType(inner, "readonly");
}
// keyof will only show up with generic functions, otherwise it gets eagerly
// resolved to a union of strings.
if (node.operator === ts.SyntaxKind.KeyOfKeyword) {
// TS 4.2 added this to enable better tracking of type aliases.
if (type.isUnion() && type.origin) {
return convertType(context, type.origin);
}
// There's probably an interface for this somewhere... I couldn't find it.
const targetType = (type as ts.Type & { type: ts.Type }).type;
return new TypeOperatorType(
convertType(context, targetType),
"keyof"
);
}
// TS drops `unique` in `unique symbol` everywhere. If someone used it, we ought
// to have a type node. This shouldn't ever happen.
return requestBugReport(context, type);
},
};
const unionConverter: TypeConverter<ts.UnionTypeNode, ts.UnionType> = {
kind: [ts.SyntaxKind.UnionType],
convert(context, node) {
return new UnionType(
node.types.map((type) => convertType(context, type))
);
},
convertType(context, type) {
// TS 4.2 added this to enable better tracking of type aliases.
if (type.origin) {
return convertType(context, type.origin);
}
return new UnionType(
type.types.map((type) => convertType(context, type))
);
},
};
const jsDocNullableTypeConverter: TypeConverter<ts.JSDocNullableType> = {
kind: [ts.SyntaxKind.JSDocNullableType],
convert(context, node) {
return new UnionType([
convertType(context, node.type),
new LiteralType(null),
]);
},
// Should be a UnionType
convertType: requestBugReport,
};
const jsDocNonNullableTypeConverter: TypeConverter<ts.JSDocNonNullableType> = {
kind: [ts.SyntaxKind.JSDocNonNullableType],
convert(context, node) {
return convertType(context, node.type);
},
// Should be a UnionType
convertType: requestBugReport,
};