-
Notifications
You must be signed in to change notification settings - Fork 583
/
Copy pathinference.go
1590 lines (1514 loc) · 72.1 KB
/
inference.go
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
package checker
import (
"slices"
"github.com/microsoft/typescript-go/internal/ast"
"github.com/microsoft/typescript-go/internal/core"
"github.com/microsoft/typescript-go/internal/jsnum"
)
type InferenceKey struct {
s TypeId
t TypeId
}
type InferenceState struct {
inferences []*InferenceInfo
originalSource *Type
originalTarget *Type
priority InferencePriority
inferencePriority InferencePriority
contravariant bool
bivariant bool
expandingFlags ExpandingFlags
propagationType *Type
visited map[InferenceKey]InferencePriority
sourceStack []*Type
targetStack []*Type
next *InferenceState
}
func (c *Checker) getInferenceState() *InferenceState {
n := c.freeinferenceState
if n == nil {
n = &InferenceState{}
}
c.freeinferenceState = n.next
return n
}
func (c *Checker) putInferenceState(n *InferenceState) {
clear(n.visited)
*n = InferenceState{
inferences: n.inferences[:0],
visited: n.visited,
sourceStack: n.sourceStack[:0],
targetStack: n.targetStack[:0],
next: c.freeinferenceState,
}
c.freeinferenceState = n
}
func (c *Checker) inferTypes(inferences []*InferenceInfo, originalSource *Type, originalTarget *Type, priority InferencePriority, contravariant bool) {
n := c.getInferenceState()
n.inferences = inferences
n.originalSource = originalSource
n.originalTarget = originalTarget
n.priority = priority
n.inferencePriority = InferencePriorityMaxValue
n.contravariant = contravariant
c.inferFromTypes(n, originalSource, originalTarget)
c.putInferenceState(n)
}
func (c *Checker) inferFromTypes(n *InferenceState, source *Type, target *Type) {
if !c.couldContainTypeVariables(target) || c.isNoInferType(target) {
return
}
if source == c.wildcardType || source == c.blockedStringType {
// We are inferring from an 'any' type. We want to infer this type for every type parameter
// referenced in the target type, so we record it as the propagation type and infer from the
// target to itself. Then, as we find candidates we substitute the propagation type.
savePropagationType := n.propagationType
n.propagationType = source
c.inferFromTypes(n, target, target)
n.propagationType = savePropagationType
return
}
if source.alias != nil && target.alias != nil && source.alias.symbol == target.alias.symbol {
if len(source.alias.typeArguments) != 0 || len(target.alias.typeArguments) != 0 {
// Source and target are types originating in the same generic type alias declaration.
// Simply infer from source type arguments to target type arguments, with defaults applied.
params := c.typeAliasLinks.Get(source.alias.symbol).typeParameters
minParams := c.getMinTypeArgumentCount(params)
sourceTypes := c.fillMissingTypeArguments(source.alias.typeArguments, params, minParams)
targetTypes := c.fillMissingTypeArguments(target.alias.typeArguments, params, minParams)
c.inferFromTypeArguments(n, sourceTypes, targetTypes, c.getAliasVariances(source.alias.symbol))
}
// And if there weren't any type arguments, there's no reason to run inference as the types must be the same.
return
}
if source == target && source.flags&TypeFlagsUnionOrIntersection != 0 {
// When source and target are the same union or intersection type, just relate each constituent
// type to itself.
for _, t := range source.Types() {
c.inferFromTypes(n, t, t)
}
return
}
if target.flags&TypeFlagsUnion != 0 && source.flags&TypeFlagsNever == 0 {
// First, infer between identically matching source and target constituents and remove the
// matching types.
tempSources, tempTargets := c.inferFromMatchingTypes(n, source.Distributed(), target.Distributed(), (*Checker).isTypeOrBaseIdenticalTo)
// Next, infer between closely matching source and target constituents and remove
// the matching types. Types closely match when they are instantiations of the same
// object type or instantiations of the same type alias.
sources, targets := c.inferFromMatchingTypes(n, tempSources, tempTargets, (*Checker).isTypeCloselyMatchedBy)
if len(targets) == 0 {
return
}
target = c.getUnionType(targets)
if len(sources) == 0 {
// All source constituents have been matched and there is nothing further to infer from.
// However, simply making no inferences is undesirable because it could ultimately mean
// inferring a type parameter constraint. Instead, make a lower priority inference from
// the full source to whatever remains in the target. For example, when inferring from
// string to 'string | T', make a lower priority inference of string for T.
c.inferWithPriority(n, source, target, InferencePriorityNakedTypeVariable)
return
}
source = c.getUnionType(sources)
} else if target.flags&TypeFlagsIntersection != 0 && !core.Every(target.Types(), c.isNonGenericObjectType) {
// We reduce intersection types unless they're simple combinations of object types. For example,
// when inferring from 'string[] & { extra: any }' to 'string[] & T' we want to remove string[] and
// infer { extra: any } for T. But when inferring to 'string[] & Iterable<T>' we want to keep the
// string[] on the source side and infer string for T.
if source.flags&TypeFlagsUnion == 0 {
var sourceTypes []*Type
if source.flags&TypeFlagsIntersection != 0 {
sourceTypes = source.Types()
} else {
sourceTypes = []*Type{source}
}
// Infer between identically matching source and target constituents and remove the matching types.
sources, targets := c.inferFromMatchingTypes(n, sourceTypes, target.Types(), (*Checker).isTypeIdenticalTo)
if len(sources) == 0 || len(targets) == 0 {
return
}
source = c.getIntersectionType(sources)
target = c.getIntersectionType(targets)
}
}
if target.flags&(TypeFlagsIndexedAccess|TypeFlagsSubstitution) != 0 {
if c.isNoInferType(target) {
return
}
target = c.getActualTypeVariable(target)
}
if target.flags&TypeFlagsTypeVariable != 0 {
// Skip inference if the source is "blocked", which is used by the language service to
// prevent inference on nodes currently being edited.
if c.isFromInferenceBlockedSource(source) {
return
}
inference := getInferenceInfoForType(n, target)
if inference != nil {
// If target is a type parameter, make an inference, unless the source type contains
// a "non-inferrable" type. Types with this flag set are markers used to prevent inference.
//
// For example:
// - anyFunctionType is a wildcard type that's used to avoid contextually typing functions;
// it's internal, so should not be exposed to the user by adding it as a candidate.
// - autoType (and autoArrayType) is a special "any" used in control flow; like anyFunctionType,
// it's internal and should not be observable.
// - silentNeverType is returned by getInferredType when instantiating a generic function for
// inference (and a type variable has no mapping).
//
// This flag is infectious; if we produce Box<never> (where never is silentNeverType), Box<never> is
// also non-inferrable.
//
// As a special case, also ignore nonInferrableAnyType, which is a special form of the any type
// used as a stand-in for binding elements when they are being inferred.
if source.objectFlags&ObjectFlagsNonInferrableType != 0 || source == c.nonInferrableAnyType {
return
}
if !inference.isFixed {
candidate := core.OrElse(n.propagationType, source)
if candidate == c.blockedStringType {
return
}
if n.priority < inference.priority {
inference.candidates = nil
inference.contraCandidates = nil
inference.topLevel = true
inference.priority = n.priority
}
if n.priority == inference.priority {
// Inferring A to [A[0]] is a zero information inference (it guarantees A becomes its constraint), but oft arises from generic argument list inferences
// By discarding it early, we can allow more fruitful results to be used instead.
if c.isTupleOfSelf(inference.typeParameter, candidate) {
return
}
// We make contravariant inferences only if we are in a pure contravariant position,
// i.e. only if we have not descended into a bivariant position.
if n.contravariant && !n.bivariant {
if !slices.Contains(inference.contraCandidates, candidate) {
inference.contraCandidates = append(inference.contraCandidates, candidate)
clearCachedInferences(n.inferences)
}
} else if !slices.Contains(inference.candidates, candidate) {
inference.candidates = append(inference.candidates, candidate)
clearCachedInferences(n.inferences)
}
}
if n.priority&InferencePriorityReturnType == 0 && target.flags&TypeFlagsTypeParameter != 0 && inference.topLevel && !c.isTypeParameterAtTopLevel(n.originalTarget, target, 0) {
inference.topLevel = false
clearCachedInferences(n.inferences)
}
}
n.inferencePriority = min(n.inferencePriority, n.priority)
return
}
// Infer to the simplified version of an indexed access, if possible, to (hopefully) expose more bare type parameters to the inference engine
simplified := c.getSimplifiedType(target, false /*writing*/)
if simplified != target {
c.inferFromTypes(n, source, simplified)
} else if target.flags&TypeFlagsIndexedAccess != 0 {
indexType := c.getSimplifiedType(target.AsIndexedAccessType().indexType, false /*writing*/)
// Generally simplifications of instantiable indexes are avoided to keep relationship checking correct, however if our target is an access, we can consider
// that key of that access to be "instantiated", since we're looking to find the infernce goal in any way we can.
if indexType.flags&TypeFlagsInstantiable != 0 {
simplified := c.distributeIndexOverObjectType(c.getSimplifiedType(target.AsIndexedAccessType().objectType, false /*writing*/), indexType, false /*writing*/)
if simplified != nil && simplified != target {
c.inferFromTypes(n, source, simplified)
}
}
}
}
switch {
case source.objectFlags&ObjectFlagsReference != 0 && target.objectFlags&ObjectFlagsReference != 0 && (source.AsTypeReference().target == target.AsTypeReference().target || c.isArrayType(source) && c.isArrayType(target)) && !(source.AsTypeReference().node != nil && target.AsTypeReference().node != nil):
// If source and target are references to the same generic type, infer from type arguments
c.inferFromTypeArguments(n, c.getTypeArguments(source), c.getTypeArguments(target), c.getVariances(source.AsTypeReference().target))
case source.flags&TypeFlagsIndex != 0 && target.flags&TypeFlagsIndex != 0:
c.inferFromContravariantTypes(n, source.AsIndexType().target, target.AsIndexType().target)
case (isLiteralType(source) || source.flags&TypeFlagsString != 0) && target.flags&TypeFlagsIndex != 0:
empty := c.createEmptyObjectTypeFromStringLiteral(source)
c.inferFromContravariantTypesWithPriority(n, empty, target.AsIndexType().target, InferencePriorityLiteralKeyof)
case source.flags&TypeFlagsIndexedAccess != 0 && target.flags&TypeFlagsIndexedAccess != 0:
c.inferFromTypes(n, source.AsIndexedAccessType().objectType, target.AsIndexedAccessType().objectType)
c.inferFromTypes(n, source.AsIndexedAccessType().indexType, target.AsIndexedAccessType().indexType)
case source.flags&TypeFlagsStringMapping != 0 && target.flags&TypeFlagsStringMapping != 0:
if source.symbol == target.symbol {
c.inferFromTypes(n, source.AsStringMappingType().target, target.AsStringMappingType().target)
}
case source.flags&TypeFlagsSubstitution != 0:
c.inferFromTypes(n, source.AsSubstitutionType().baseType, target)
// Make substitute inference at a lower priority
c.inferWithPriority(n, c.getSubstitutionIntersection(source), target, InferencePrioritySubstituteSource)
case target.flags&TypeFlagsConditional != 0:
c.invokeOnce(n, source, target, (*Checker).inferToConditionalType)
case target.flags&TypeFlagsUnionOrIntersection != 0:
c.inferToMultipleTypes(n, source, target.Types(), target.flags)
case source.flags&TypeFlagsUnion != 0:
// Source is a union or intersection type, infer from each constituent type
for _, sourceType := range source.Types() {
c.inferFromTypes(n, sourceType, target)
}
case target.flags&TypeFlagsTemplateLiteral != 0:
c.inferToTemplateLiteralType(n, source, target.AsTemplateLiteralType())
default:
source = c.getReducedType(source)
if c.isGenericMappedType(source) && c.isGenericMappedType(target) {
c.invokeOnce(n, source, target, (*Checker).inferFromGenericMappedTypes)
}
if !(n.priority&InferencePriorityNoConstraints != 0 && source.flags&(TypeFlagsIntersection|TypeFlagsInstantiable) != 0) {
apparentSource := c.getApparentType(source)
// getApparentType can return _any_ type, since an indexed access or conditional may simplify to any other type.
// If that occurs and it doesn't simplify to an object or intersection, we'll need to restart `inferFromTypes`
// with the simplified source.
if apparentSource != source && apparentSource.flags&(TypeFlagsObject|TypeFlagsIntersection) == 0 {
c.inferFromTypes(n, apparentSource, target)
return
}
source = apparentSource
}
if source.flags&(TypeFlagsObject|TypeFlagsIntersection) != 0 {
c.invokeOnce(n, source, target, (*Checker).inferFromObjectTypes)
}
}
}
func (c *Checker) inferFromTypeArguments(n *InferenceState, sourceTypes []*Type, targetTypes []*Type, variances []VarianceFlags) {
for i := range min(len(sourceTypes), len(targetTypes)) {
if i < len(variances) && variances[i]&VarianceFlagsVarianceMask == VarianceFlagsContravariant {
c.inferFromContravariantTypes(n, sourceTypes[i], targetTypes[i])
} else {
c.inferFromTypes(n, sourceTypes[i], targetTypes[i])
}
}
}
func (c *Checker) inferWithPriority(n *InferenceState, source *Type, target *Type, newPriority InferencePriority) {
savePriority := n.priority
n.priority |= newPriority
c.inferFromTypes(n, source, target)
n.priority = savePriority
}
func (c *Checker) inferFromContravariantTypesWithPriority(n *InferenceState, source *Type, target *Type, newPriority InferencePriority) {
savePriority := n.priority
n.priority |= newPriority
c.inferFromContravariantTypes(n, source, target)
n.priority = savePriority
}
func (c *Checker) inferFromContravariantTypes(n *InferenceState, source *Type, target *Type) {
n.contravariant = !n.contravariant
c.inferFromTypes(n, source, target)
n.contravariant = !n.contravariant
}
func (c *Checker) inferFromContravariantTypesIfStrictFunctionTypes(n *InferenceState, source *Type, target *Type) {
if c.strictFunctionTypes || n.priority&InferencePriorityAlwaysStrict != 0 {
c.inferFromContravariantTypes(n, source, target)
} else {
c.inferFromTypes(n, source, target)
}
}
// Ensure an inference action is performed only once for the given source and target types.
// This includes two things:
// Avoiding inferring between the same pair of source and target types,
// and avoiding circularly inferring between source and target types.
// For an example of the last, consider if we are inferring between source type
// `type Deep<T> = { next: Deep<Deep<T>> }` and target type `type Loop<U> = { next: Loop<U> }`.
// We would then infer between the types of the `next` property: `Deep<Deep<T>>` = `{ next: Deep<Deep<Deep<T>>> }` and `Loop<U>` = `{ next: Loop<U> }`.
// We will then infer again between the types of the `next` property:
// `Deep<Deep<Deep<T>>>` and `Loop<U>`, and so on, such that we would be forever inferring
// between instantiations of the same types `Deep` and `Loop`.
// In particular, we would be inferring from increasingly deep instantiations of `Deep` to `Loop`,
// such that we would go on inferring forever, even though we would never infer
// between the same pair of types.
func (c *Checker) invokeOnce(n *InferenceState, source *Type, target *Type, action func(c *Checker, n *InferenceState, source *Type, target *Type)) {
key := InferenceKey{s: source.id, t: target.id}
if status, ok := n.visited[key]; ok {
n.inferencePriority = min(n.inferencePriority, status)
return
}
if n.visited == nil {
n.visited = make(map[InferenceKey]InferencePriority)
}
n.visited[key] = InferencePriorityCircularity
saveInferencePriority := n.inferencePriority
n.inferencePriority = InferencePriorityMaxValue
// We stop inferring and report a circularity if we encounter duplicate recursion identities on both
// the source side and the target side.
saveExpandingFlags := n.expandingFlags
n.sourceStack = append(n.sourceStack, source)
n.targetStack = append(n.targetStack, target)
if c.isDeeplyNestedType(source, n.sourceStack, 2) {
n.expandingFlags |= ExpandingFlagsSource
}
if c.isDeeplyNestedType(target, n.targetStack, 2) {
n.expandingFlags |= ExpandingFlagsTarget
}
if n.expandingFlags != ExpandingFlagsBoth {
action(c, n, source, target)
} else {
n.inferencePriority = InferencePriorityCircularity
}
n.targetStack = n.targetStack[:len(n.targetStack)-1]
n.sourceStack = n.sourceStack[:len(n.sourceStack)-1]
n.expandingFlags = saveExpandingFlags
n.visited[key] = n.inferencePriority
n.inferencePriority = min(n.inferencePriority, saveInferencePriority)
}
func (c *Checker) inferFromMatchingTypes(n *InferenceState, sources []*Type, targets []*Type, matches func(c *Checker, s *Type, t *Type) bool) ([]*Type, []*Type) {
var matchedSources []*Type
var matchedTargets []*Type
for _, t := range targets {
for _, s := range sources {
if matches(c, s, t) {
c.inferFromTypes(n, s, t)
matchedSources = core.AppendIfUnique(matchedSources, s)
matchedTargets = core.AppendIfUnique(matchedTargets, t)
}
}
}
if len(matchedSources) != 0 {
sources = core.Filter(sources, func(t *Type) bool { return !slices.Contains(matchedSources, t) })
}
if len(matchedTargets) != 0 {
targets = core.Filter(targets, func(t *Type) bool { return !slices.Contains(matchedTargets, t) })
}
return sources, targets
}
func (c *Checker) inferToMultipleTypes(n *InferenceState, source *Type, targets []*Type, targetFlags TypeFlags) {
typeVariableCount := 0
if targetFlags&TypeFlagsUnion != 0 {
var nakedTypeVariable *Type
sources := source.Distributed()
matched := make([]bool, len(sources))
inferenceCircularity := false
// First infer to types that are not naked type variables. For each source type we
// track whether inferences were made from that particular type to some target with
// equal priority (i.e. of equal quality) to what we would infer for a naked type
// parameter.
for _, t := range targets {
if getInferenceInfoForType(n, t) != nil {
nakedTypeVariable = t
typeVariableCount++
} else {
for i := range sources {
saveInferencePriority := n.inferencePriority
n.inferencePriority = InferencePriorityMaxValue
c.inferFromTypes(n, sources[i], t)
if n.inferencePriority == n.priority {
matched[i] = true
}
inferenceCircularity = inferenceCircularity || n.inferencePriority == InferencePriorityCircularity
n.inferencePriority = min(n.inferencePriority, saveInferencePriority)
}
}
}
if typeVariableCount == 0 {
// If every target is an intersection of types containing a single naked type variable,
// make a lower priority inference to that type variable. This handles inferring from
// 'A | B' to 'T & (X | Y)' where we want to infer 'A | B' for T.
intersectionTypeVariable := getSingleTypeVariableFromIntersectionTypes(n, targets)
if intersectionTypeVariable != nil {
c.inferWithPriority(n, source, intersectionTypeVariable, InferencePriorityNakedTypeVariable)
}
return
}
// If the target has a single naked type variable and no inference circularities were
// encountered above (meaning we explored the types fully), create a union of the source
// types from which no inferences have been made so far and infer from that union to the
// naked type variable.
if typeVariableCount == 1 && !inferenceCircularity {
var unmatched []*Type
for i, s := range sources {
if !matched[i] {
unmatched = append(unmatched, s)
}
}
if len(unmatched) != 0 {
c.inferFromTypes(n, c.getUnionType(unmatched), nakedTypeVariable)
return
}
}
} else {
// We infer from types that are not naked type variables first so that inferences we
// make from nested naked type variables and given slightly higher priority by virtue
// of being first in the candidates array.
for _, t := range targets {
if getInferenceInfoForType(n, t) != nil {
typeVariableCount++
} else {
c.inferFromTypes(n, source, t)
}
}
}
// Inferences directly to naked type variables are given lower priority as they are
// less specific. For example, when inferring from Promise<string> to T | Promise<T>,
// we want to infer string for T, not Promise<string> | string. For intersection types
// we only infer to single naked type variables.
if targetFlags&TypeFlagsIntersection != 0 && typeVariableCount == 1 || targetFlags&TypeFlagsIntersection == 0 && typeVariableCount > 0 {
for _, t := range targets {
if getInferenceInfoForType(n, t) != nil {
c.inferWithPriority(n, source, t, InferencePriorityNakedTypeVariable)
}
}
}
}
func getSingleTypeVariableFromIntersectionTypes(n *InferenceState, types []*Type) *Type {
var typeVariable *Type
for _, t := range types {
if t.flags&TypeFlagsIntersection == 0 {
return nil
}
v := core.Find(t.Types(), func(t *Type) bool { return getInferenceInfoForType(n, t) != nil })
if v == nil || typeVariable != nil && v != typeVariable {
return nil
}
typeVariable = v
}
return typeVariable
}
func (c *Checker) inferToMultipleTypesWithPriority(n *InferenceState, source *Type, targets []*Type, targetFlags TypeFlags, newPriority InferencePriority) {
savePriority := n.priority
n.priority |= newPriority
c.inferToMultipleTypes(n, source, targets, targetFlags)
n.priority = savePriority
}
func (c *Checker) inferToConditionalType(n *InferenceState, source *Type, target *Type) {
if source.flags&TypeFlagsConditional != 0 {
c.inferFromTypes(n, source.AsConditionalType().checkType, target.AsConditionalType().checkType)
c.inferFromTypes(n, source.AsConditionalType().extendsType, target.AsConditionalType().extendsType)
c.inferFromTypes(n, c.getTrueTypeFromConditionalType(source), c.getTrueTypeFromConditionalType(target))
c.inferFromTypes(n, c.getFalseTypeFromConditionalType(source), c.getFalseTypeFromConditionalType(target))
} else {
targetTypes := []*Type{c.getTrueTypeFromConditionalType(target), c.getFalseTypeFromConditionalType(target)}
c.inferToMultipleTypesWithPriority(n, source, targetTypes, target.flags, core.IfElse(n.contravariant, InferencePriorityContravariantConditional, 0))
}
}
func (c *Checker) inferToTemplateLiteralType(n *InferenceState, source *Type, target *TemplateLiteralType) {
matches := c.inferTypesFromTemplateLiteralType(source, target)
types := target.types
// When the target template literal contains only placeholders (meaning that inference is intended to extract
// single characters and remainder strings) and inference fails to produce matches, we want to infer 'never' for
// each placeholder such that instantiation with the inferred value(s) produces 'never', a type for which an
// assignment check will fail. If we make no inferences, we'll likely end up with the constraint 'string' which,
// upon instantiation, would collapse all the placeholders to just 'string', and an assignment check might
// succeed. That would be a pointless and confusing outcome.
if len(matches) != 0 || core.Every(target.texts, func(s string) bool { return s == "" }) {
for i, target := range types {
var source *Type
if len(matches) != 0 {
source = matches[i]
} else {
source = c.neverType
}
// If we are inferring from a string literal type to a type variable whose constraint includes one of the
// allowed template literal placeholder types, infer from a literal type corresponding to the constraint.
if source.flags&TypeFlagsStringLiteral != 0 && target.flags&TypeFlagsTypeVariable != 0 {
if inferenceContext := getInferenceInfoForType(n, target); inferenceContext != nil {
if constraint := c.getBaseConstraintOfType(inferenceContext.typeParameter); constraint != nil && !IsTypeAny(constraint) {
allTypeFlags := TypeFlagsNone
for _, t := range constraint.Distributed() {
allTypeFlags |= t.flags
}
// If the constraint contains `string`, we don't need to look for a more preferred type
if allTypeFlags&TypeFlagsString == 0 {
str := getStringLiteralValue(source)
// If the type contains `number` or a number literal and the string isn't a valid number, exclude numbers
if allTypeFlags&TypeFlagsNumberLike != 0 && !isValidNumberString(str, true /*roundTripOnly*/) {
allTypeFlags &^= TypeFlagsNumberLike
}
// If the type contains `bigint` or a bigint literal and the string isn't a valid bigint, exclude bigints
if allTypeFlags&TypeFlagsBigIntLike != 0 && !isValidBigIntString(str, true /*roundTripOnly*/) {
allTypeFlags &^= TypeFlagsBigIntLike
}
choose := func(left *Type, right *Type) *Type {
switch {
case right.flags&allTypeFlags == 0:
return left
case left.flags&TypeFlagsString != 0:
return left
case right.flags&TypeFlagsString != 0:
return source
case left.flags&TypeFlagsTemplateLiteral != 0:
return left
case right.flags&TypeFlagsTemplateLiteral != 0 && c.isTypeMatchedByTemplateLiteralType(source, right.AsTemplateLiteralType()):
return source
case left.flags&TypeFlagsStringMapping != 0:
return left
case right.flags&TypeFlagsStringMapping != 0 && str == applyStringMapping(right.symbol, str):
return source
case left.flags&TypeFlagsStringLiteral != 0:
return left
case right.flags&TypeFlagsStringLiteral != 0 && getStringLiteralValue(right) == str:
return right
case left.flags&TypeFlagsNumber != 0:
return left
case right.flags&TypeFlagsNumber != 0:
return c.getNumberLiteralType(jsnum.FromString(str))
case left.flags&TypeFlagsEnum != 0:
return left
case right.flags&TypeFlagsEnum != 0:
return c.getNumberLiteralType(jsnum.FromString(str))
case left.flags&TypeFlagsNumberLiteral != 0:
return left
case right.flags&TypeFlagsNumberLiteral != 0 && getNumberLiteralValue(right) == jsnum.FromString(str):
return right
case left.flags&TypeFlagsBigInt != 0:
return left
case right.flags&TypeFlagsBigInt != 0:
return c.parseBigIntLiteralType(str)
case left.flags&TypeFlagsBigIntLiteral != 0:
return left
case right.flags&TypeFlagsBigIntLiteral != 0 && pseudoBigIntToString(getBigIntLiteralValue(right)) == str:
return right
case left.flags&TypeFlagsBoolean != 0:
return left
case right.flags&TypeFlagsBoolean != 0:
switch str {
case "true":
return c.trueType
case "false":
return c.falseType
default:
return c.booleanType
}
case left.flags&TypeFlagsBooleanLiteral != 0:
return left
case right.flags&TypeFlagsBooleanLiteral != 0 && core.IfElse(getBooleanLiteralValue(right), "true", "false") == str:
return right
case left.flags&TypeFlagsUndefined != 0:
return left
case right.flags&TypeFlagsUndefined != 0 && right.AsIntrinsicType().intrinsicName == str:
return right
case left.flags&TypeFlagsNull != 0:
return left
case right.flags&TypeFlagsNull != 0 && right.AsIntrinsicType().intrinsicName == str:
return right
default:
return left
}
}
matchingType := c.neverType
for _, t := range constraint.Distributed() {
matchingType = choose(matchingType, t)
}
if matchingType.flags&TypeFlagsNever == 0 {
c.inferFromTypes(n, matchingType, target)
continue
}
}
}
}
}
c.inferFromTypes(n, source, target)
}
}
}
func (c *Checker) inferFromGenericMappedTypes(n *InferenceState, source *Type, target *Type) {
// The source and target types are generic types { [P in S]: X } and { [P in T]: Y }, so we infer
// from S to T and from X to Y.
c.inferFromTypes(n, c.getConstraintTypeFromMappedType(source), c.getConstraintTypeFromMappedType(target))
c.inferFromTypes(n, c.getTemplateTypeFromMappedType(source), c.getTemplateTypeFromMappedType(target))
sourceNameType := c.getNameTypeFromMappedType(source)
targetNameType := c.getNameTypeFromMappedType(target)
if sourceNameType != nil && targetNameType != nil {
c.inferFromTypes(n, sourceNameType, targetNameType)
}
}
func (c *Checker) inferFromObjectTypes(n *InferenceState, source *Type, target *Type) {
if source.objectFlags&ObjectFlagsReference != 0 && target.objectFlags&ObjectFlagsReference != 0 && (source.Target() == target.Target() || c.isArrayType(source) && c.isArrayType(target)) {
// If source and target are references to the same generic type, infer from type arguments
c.inferFromTypeArguments(n, c.getTypeArguments(source), c.getTypeArguments(target), c.getVariances(source.Target()))
return
}
if c.isGenericMappedType(source) && c.isGenericMappedType(target) {
c.inferFromGenericMappedTypes(n, source, target)
}
if target.objectFlags&ObjectFlagsMapped != 0 && target.AsMappedType().declaration.NameType == nil {
constraintType := c.getConstraintTypeFromMappedType(target)
if c.inferToMappedType(n, source, target, constraintType) {
return
}
}
// Infer from the members of source and target only if the two types are possibly related
if c.typesDefinitelyUnrelated(source, target) {
return
}
if c.isArrayOrTupleType(source) {
if isTupleType(target) {
sourceArity := c.getTypeReferenceArity(source)
targetArity := c.getTypeReferenceArity(target)
elementTypes := c.getTypeArguments(target)
elementInfos := target.TargetTupleType().elementInfos
// When source and target are tuple types with the same structure (fixed, variadic, and rest are matched
// to the same kind in each position), simply infer between the element types.
if isTupleType(source) && c.isTupleTypeStructureMatching(source, target) {
for i := range targetArity {
c.inferFromTypes(n, c.getTypeArguments(source)[i], elementTypes[i])
}
return
}
startLength := 0
endLength := 0
if isTupleType(source) {
startLength = min(source.TargetTupleType().fixedLength, target.TargetTupleType().fixedLength)
if target.TargetTupleType().combinedFlags&ElementFlagsVariable != 0 {
endLength = min(getEndElementCount(source.TargetTupleType(), ElementFlagsFixed), getEndElementCount(target.TargetTupleType(), ElementFlagsFixed))
}
}
// Infer between starting fixed elements.
for i := range startLength {
c.inferFromTypes(n, c.getTypeArguments(source)[i], elementTypes[i])
}
if !isTupleType(source) || sourceArity-startLength-endLength == 1 && source.TargetTupleType().elementInfos[startLength].flags&ElementFlagsRest != 0 {
// Single rest element remains in source, infer from that to every element in target
restType := c.getTypeArguments(source)[startLength]
for i := startLength; i < targetArity-endLength; i++ {
t := restType
if elementInfos[i].flags&ElementFlagsVariadic != 0 {
t = c.createArrayType(t)
}
c.inferFromTypes(n, t, elementTypes[i])
}
} else {
middleLength := targetArity - startLength - endLength
if middleLength == 2 {
if elementInfos[startLength].flags&elementInfos[startLength+1].flags&ElementFlagsVariadic != 0 {
// Middle of target is [...T, ...U] and source is tuple type
targetInfo := getInferenceInfoForType(n, elementTypes[startLength])
if targetInfo != nil && targetInfo.impliedArity >= 0 {
// Infer slices from source based on implied arity of T.
c.inferFromTypes(n, c.sliceTupleType(source, startLength, endLength+sourceArity-targetInfo.impliedArity), elementTypes[startLength])
c.inferFromTypes(n, c.sliceTupleType(source, startLength+targetInfo.impliedArity, endLength), elementTypes[startLength+1])
}
} else if elementInfos[startLength].flags&ElementFlagsVariadic != 0 && elementInfos[startLength+1].flags&ElementFlagsRest != 0 {
// Middle of target is [...T, ...rest] and source is tuple type
// if T is constrained by a fixed-size tuple we might be able to use its arity to infer T
if info := getInferenceInfoForType(n, elementTypes[startLength]); info != nil {
constraint := c.getBaseConstraintOfType(info.typeParameter)
if constraint != nil && isTupleType(constraint) && constraint.TargetTupleType().combinedFlags&ElementFlagsVariable == 0 {
impliedArity := constraint.TargetTupleType().fixedLength
c.inferFromTypes(n, c.sliceTupleType(source, startLength, sourceArity-(startLength+impliedArity)), elementTypes[startLength])
c.inferFromTypes(n, c.getElementTypeOfSliceOfTupleType(source, startLength+impliedArity, endLength, false, false), elementTypes[startLength+1])
}
}
} else if elementInfos[startLength].flags&ElementFlagsRest != 0 && elementInfos[startLength+1].flags&ElementFlagsVariadic != 0 {
// Middle of target is [...rest, ...T] and source is tuple type
// if T is constrained by a fixed-size tuple we might be able to use its arity to infer T
if info := getInferenceInfoForType(n, elementTypes[startLength+1]); info != nil {
constraint := c.getBaseConstraintOfType(info.typeParameter)
if constraint != nil && isTupleType(constraint) && constraint.TargetTupleType().combinedFlags&ElementFlagsVariable == 0 {
impliedArity := constraint.TargetTupleType().fixedLength
endIndex := sourceArity - getEndElementCount(target.TargetTupleType(), ElementFlagsFixed)
startIndex := endIndex - impliedArity
trailingSlice := c.createTupleTypeEx(c.getTypeArguments(source)[startIndex:endIndex], source.TargetTupleType().elementInfos[startIndex:endIndex], false /*readonly*/)
c.inferFromTypes(n, c.getElementTypeOfSliceOfTupleType(source, startLength, endLength+impliedArity, false, false), elementTypes[startLength])
c.inferFromTypes(n, trailingSlice, elementTypes[startLength+1])
}
}
}
} else if middleLength == 1 && elementInfos[startLength].flags&ElementFlagsVariadic != 0 {
// Middle of target is exactly one variadic element. Infer the slice between the fixed parts in the source.
// If target ends in optional element(s), make a lower priority a speculative inference.
priority := core.IfElse(elementInfos[targetArity-1].flags&ElementFlagsOptional != 0, InferencePrioritySpeculativeTuple, 0)
sourceSlice := c.sliceTupleType(source, startLength, endLength)
c.inferWithPriority(n, sourceSlice, elementTypes[startLength], priority)
} else if middleLength == 1 && elementInfos[startLength].flags&ElementFlagsRest != 0 {
// Middle of target is exactly one rest element. If middle of source is not empty, infer union of middle element types.
restType := c.getElementTypeOfSliceOfTupleType(source, startLength, endLength, false, false)
if restType != nil {
c.inferFromTypes(n, restType, elementTypes[startLength])
}
}
}
// Infer between ending fixed elements
for i := range endLength {
c.inferFromTypes(n, c.getTypeArguments(source)[sourceArity-i-1], elementTypes[targetArity-i-1])
}
return
}
if c.isArrayType(target) {
c.inferFromIndexTypes(n, source, target)
return
}
}
c.inferFromProperties(n, source, target)
c.inferFromSignatures(n, source, target, SignatureKindCall)
c.inferFromSignatures(n, source, target, SignatureKindConstruct)
c.inferFromIndexTypes(n, source, target)
}
func (c *Checker) inferFromProperties(n *InferenceState, source *Type, target *Type) {
properties := c.getPropertiesOfObjectType(target)
for _, targetProp := range properties {
sourceProp := c.getPropertyOfType(source, targetProp.Name)
if sourceProp != nil && !core.Some(sourceProp.Declarations, c.hasSkipDirectInferenceFlag) {
c.inferFromTypes(n, c.removeMissingType(c.getTypeOfSymbol(sourceProp), sourceProp.Flags&ast.SymbolFlagsOptional != 0), c.removeMissingType(c.getTypeOfSymbol(targetProp), targetProp.Flags&ast.SymbolFlagsOptional != 0))
}
}
}
func (c *Checker) inferFromSignatures(n *InferenceState, source *Type, target *Type, kind SignatureKind) {
sourceSignatures := c.getSignaturesOfType(source, kind)
sourceLen := len(sourceSignatures)
if sourceLen > 0 {
// We match source and target signatures from the bottom up, and if the source has fewer signatures
// than the target, we infer from the first source signature to the excess target signatures.
targetSignatures := c.getSignaturesOfType(target, kind)
targetLen := len(targetSignatures)
for i := range targetLen {
sourceIndex := max(sourceLen-targetLen+i, 0)
c.inferFromSignature(n, c.getBaseSignature(sourceSignatures[sourceIndex]), c.getErasedSignature(targetSignatures[i]))
}
}
}
func (c *Checker) inferFromSignature(n *InferenceState, source *Signature, target *Signature) {
if source.flags&SignatureFlagsIsNonInferrable == 0 {
saveBivariant := n.bivariant
kind := ast.KindUnknown
if target.declaration != nil {
kind = target.declaration.Kind
}
// Once we descend into a bivariant signature we remain bivariant for all nested inferences
n.bivariant = n.bivariant || kind == ast.KindMethodDeclaration || kind == ast.KindMethodSignature || kind == ast.KindConstructor
c.applyToParameterTypes(source, target, func(s, t *Type) { c.inferFromContravariantTypesIfStrictFunctionTypes(n, s, t) })
n.bivariant = saveBivariant
}
c.applyToReturnTypes(source, target, func(s, t *Type) { c.inferFromTypes(n, s, t) })
}
func (c *Checker) applyToParameterTypes(source *Signature, target *Signature, callback func(s *Type, t *Type)) {
sourceCount := c.getParameterCount(source)
targetCount := c.getParameterCount(target)
sourceRestType := c.getEffectiveRestType(source)
targetRestType := c.getEffectiveRestType(target)
targetNonRestCount := targetCount
if targetRestType != nil {
targetNonRestCount--
}
paramCount := targetNonRestCount
if sourceRestType == nil {
paramCount = min(sourceCount, targetNonRestCount)
}
sourceThisType := c.getThisTypeOfSignature(source)
if sourceThisType != nil {
targetThisType := c.getThisTypeOfSignature(target)
if targetThisType != nil {
callback(sourceThisType, targetThisType)
}
}
for i := range paramCount {
callback(c.getTypeAtPosition(source, i), c.getTypeAtPosition(target, i))
}
if targetRestType != nil {
callback(c.getRestTypeAtPosition(source, paramCount, c.isConstTypeVariable(targetRestType, 0) && !someType(targetRestType, c.isMutableArrayLikeType) /*readonly*/), targetRestType)
}
}
func (c *Checker) applyToReturnTypes(source *Signature, target *Signature, callback func(s *Type, t *Type)) {
targetTypePredicate := c.getTypePredicateOfSignature(target)
if targetTypePredicate != nil {
sourceTypePredicate := c.getTypePredicateOfSignature(source)
if sourceTypePredicate != nil && c.typePredicateKindsMatch(sourceTypePredicate, targetTypePredicate) && sourceTypePredicate.t != nil && targetTypePredicate.t != nil {
callback(sourceTypePredicate.t, targetTypePredicate.t)
return
}
}
targetReturnType := c.getReturnTypeOfSignature(target)
if c.couldContainTypeVariables(targetReturnType) {
callback(c.getReturnTypeOfSignature(source), targetReturnType)
}
}
func (c *Checker) inferFromIndexTypes(n *InferenceState, source *Type, target *Type) {
// Inferences across mapped type index signatures are pretty much the same a inferences to homomorphic variables
priority := InferencePriorityNone
if source.objectFlags&target.objectFlags&ObjectFlagsMapped != 0 {
priority = InferencePriorityHomomorphicMappedType
}
indexInfos := c.getIndexInfosOfType(target)
if c.isObjectTypeWithInferableIndex(source) {
for _, targetInfo := range indexInfos {
var propTypes []*Type
for _, prop := range c.getPropertiesOfType(source) {
if c.isApplicableIndexType(c.getLiteralTypeFromProperty(prop, TypeFlagsStringOrNumberLiteralOrUnique, false), targetInfo.keyType) {
propType := c.getTypeOfSymbol(prop)
if prop.Flags&ast.SymbolFlagsOptional != 0 {
propType = c.removeMissingOrUndefinedType(propType)
}
propTypes = append(propTypes, propType)
}
}
for _, info := range c.getIndexInfosOfType(source) {
if c.isApplicableIndexType(info.keyType, targetInfo.keyType) {
propTypes = append(propTypes, info.valueType)
}
}
if len(propTypes) != 0 {
c.inferWithPriority(n, c.getUnionType(propTypes), targetInfo.valueType, priority)
}
}
}
for _, targetInfo := range indexInfos {
sourceInfo := c.getApplicableIndexInfo(source, targetInfo.keyType)
if sourceInfo != nil {
c.inferWithPriority(n, sourceInfo.valueType, targetInfo.valueType, priority)
}
}
}
func (c *Checker) inferToMappedType(n *InferenceState, source *Type, target *Type, constraintType *Type) bool {
if constraintType.flags&TypeFlagsUnion != 0 || constraintType.flags&TypeFlagsIntersection != 0 {
result := false
for _, t := range constraintType.Types() {
result = core.OrElse(c.inferToMappedType(n, source, target, t), result)
}
return result
}
if constraintType.flags&TypeFlagsIndex != 0 {
// We're inferring from some source type S to a homomorphic mapped type { [P in keyof T]: X },
// where T is a type variable. Use inferTypeForHomomorphicMappedType to infer a suitable source
// type and then make a secondary inference from that type to T. We make a secondary inference
// such that direct inferences to T get priority over inferences to Partial<T>, for example.
inference := getInferenceInfoForType(n, constraintType.AsIndexType().target)
if inference != nil && !inference.isFixed && !c.isFromInferenceBlockedSource(source) {
inferredType := c.inferTypeForHomomorphicMappedType(source, target, constraintType)
if inferredType != nil {
// We assign a lower priority to inferences made from types containing non-inferrable
// types because we may only have a partial result (i.e. we may have failed to make
// reverse inferences for some properties).
c.inferWithPriority(n, inferredType, inference.typeParameter, core.IfElse(source.objectFlags&ObjectFlagsNonInferrableType != 0, InferencePriorityPartialHomomorphicMappedType, InferencePriorityHomomorphicMappedType))
}
}
return true
}
if constraintType.flags&TypeFlagsTypeParameter != 0 {
// We're inferring from some source type S to a mapped type { [P in K]: X }, where K is a type
// parameter. First infer from 'keyof S' to K.
c.inferWithPriority(n, c.getIndexTypeEx(source, core.IfElse(c.patternForType[source] != nil, IndexFlagsNoIndexSignatures, IndexFlagsNone)), constraintType, InferencePriorityMappedTypeConstraint)
// If K is constrained to a type C, also infer to C. Thus, for a mapped type { [P in K]: X },
// where K extends keyof T, we make the same inferences as for a homomorphic mapped type
// { [P in keyof T]: X }. This enables us to make meaningful inferences when the target is a
// Pick<T, K>.
extendedConstraint := c.getConstraintOfType(constraintType)
if extendedConstraint != nil && c.inferToMappedType(n, source, target, extendedConstraint) {
return true
}
// If no inferences can be made to K's constraint, infer from a union of the property types
// in the source to the template type X.
propTypes := core.Map(c.getPropertiesOfType(source), c.getTypeOfSymbol)
indexTypes := core.Map(c.getIndexInfosOfType(source), func(info *IndexInfo) *Type {
if info != c.enumNumberIndexInfo {
return info.valueType
}
return c.neverType
})
c.inferFromTypes(n, c.getUnionType(core.Concatenate(propTypes, indexTypes)), c.getTemplateTypeFromMappedType(target))
return true
}
return false
}
// Infer a suitable input type for a homomorphic mapped type { [P in keyof T]: X }. We construct
// an object type with the same set of properties as the source type, where the type of each
// property is computed by inferring from the source property type to X for the type
// variable T[P] (i.e. we treat the type T[P] as the type variable we're inferring for).
func (c *Checker) inferTypeForHomomorphicMappedType(source *Type, target *Type, constraint *Type) *Type {
key := ReverseMappedTypeKey{sourceId: source.id, targetId: target.id, constraintId: constraint.id}
if cached := c.reverseHomomorphicMappedCache[key]; cached != nil {
return cached
}
t := c.createReverseMappedType(source, target, constraint)
c.reverseHomomorphicMappedCache[key] = t
return t
}
func (c *Checker) createReverseMappedType(source *Type, target *Type, constraint *Type) *Type {
// We consider a source type reverse mappable if it has a string index signature or if
// it has one or more properties and is of a partially inferable type.
if !(c.getIndexInfoOfType(source, c.stringType) != nil || len(c.getPropertiesOfType(source)) != 0 && c.isPartiallyInferableType(source)) {
return nil
}
// For arrays and tuples we infer new arrays and tuples where the reverse mapping has been
// applied to the element type(s).
if c.isArrayType(source) {
elementType := c.inferReverseMappedType(c.getTypeArguments(source)[0], target, constraint)
if elementType == nil {
return nil
}
return c.createArrayTypeEx(elementType, c.isReadonlyArrayType(source))
}
if isTupleType(source) {
elementTypes := core.Map(c.getElementTypes(source), func(t *Type) *Type {
return c.inferReverseMappedType(t, target, constraint)
})
if !core.Every(elementTypes, func(t *Type) bool { return t != nil }) {
return nil
}
elementInfos := source.TargetTupleType().elementInfos
if getMappedTypeModifiers(target)&MappedTypeModifiersIncludeOptional != 0 {
elementInfos = core.SameMap(elementInfos, func(info TupleElementInfo) TupleElementInfo {
if info.flags&ElementFlagsOptional != 0 {
return TupleElementInfo{flags: ElementFlagsRequired, labeledDeclaration: info.labeledDeclaration}
}
return info
})
}
return c.createTupleTypeEx(elementTypes, elementInfos, source.TargetTupleType().readonly)
}
// For all other object types we infer a new object type where the reverse mapping has been
// applied to the type of each property.
reversed := c.newObjectType(ObjectFlagsReverseMapped|ObjectFlagsAnonymous, nil /*symbol*/)
reversed.AsReverseMappedType().source = source
reversed.AsReverseMappedType().mappedType = target
reversed.AsReverseMappedType().constraintType = constraint
return reversed
}
// We consider a type to be partially inferable if it isn't marked non-inferable or if it is
// an object literal type with at least one property of an inferable type. For example, an object
// literal { a: 123, b: x => true } is marked non-inferable because it contains a context sensitive
// arrow function, but is considered partially inferable because property 'a' has an inferable type.
func (c *Checker) isPartiallyInferableType(t *Type) bool {
return t.objectFlags&ObjectFlagsNonInferrableType == 0 || isObjectLiteralType(t) && core.Some(c.getPropertiesOfType(t), func(prop *ast.Symbol) bool {
return c.isPartiallyInferableType(c.getTypeOfSymbol(prop))
}) || isTupleType(t) && core.Some(c.getElementTypes(t), c.isPartiallyInferableType)
}
func (c *Checker) inferReverseMappedType(source *Type, target *Type, constraint *Type) *Type {
key := ReverseMappedTypeKey{sourceId: source.id, targetId: target.id, constraintId: constraint.id}
if cached, ok := c.reverseMappedCache[key]; ok {
return core.OrElse(cached, c.unknownType)
}