-
Notifications
You must be signed in to change notification settings - Fork 583
/
Copy pathrelater.go
4901 lines (4688 loc) · 224 KB
/
relater.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"
"strconv"
"strings"
"github.com/microsoft/typescript-go/internal/ast"
"github.com/microsoft/typescript-go/internal/binder"
"github.com/microsoft/typescript-go/internal/core"
"github.com/microsoft/typescript-go/internal/diagnostics"
"github.com/microsoft/typescript-go/internal/jsnum"
"github.com/microsoft/typescript-go/internal/scanner"
)
type SignatureCheckMode uint32
const (
SignatureCheckModeNone SignatureCheckMode = 0
SignatureCheckModeBivariantCallback SignatureCheckMode = 1 << 0
SignatureCheckModeStrictCallback SignatureCheckMode = 1 << 1
SignatureCheckModeIgnoreReturnTypes SignatureCheckMode = 1 << 2
SignatureCheckModeStrictArity SignatureCheckMode = 1 << 3
SignatureCheckModeStrictTopSignature SignatureCheckMode = 1 << 4
SignatureCheckModeCallback SignatureCheckMode = SignatureCheckModeBivariantCallback | SignatureCheckModeStrictCallback
)
type MinArgumentCountFlags uint32
const (
MinArgumentCountFlagsNone MinArgumentCountFlags = 0
MinArgumentCountFlagsStrongArityForUntypedJS MinArgumentCountFlags = 1 << 0
MinArgumentCountFlagsVoidIsNonOptional MinArgumentCountFlags = 1 << 1
)
type IntersectionState uint32
const (
IntersectionStateNone IntersectionState = 0
IntersectionStateSource IntersectionState = 1 << 0 // Source type is a constituent of an outer intersection
IntersectionStateTarget IntersectionState = 1 << 1 // Target type is a constituent of an outer intersection
)
type RecursionFlags uint32
const (
RecursionFlagsNone RecursionFlags = 0
RecursionFlagsSource RecursionFlags = 1 << 0
RecursionFlagsTarget RecursionFlags = 1 << 1
RecursionFlagsBoth = RecursionFlagsSource | RecursionFlagsTarget
)
type ExpandingFlags uint8
const (
ExpandingFlagsNone ExpandingFlags = 0
ExpandingFlagsSource ExpandingFlags = 1 << 0
ExpandingFlagsTarget ExpandingFlags = 1 << 1
ExpandingFlagsBoth = ExpandingFlagsSource | ExpandingFlagsTarget
)
type RelationComparisonResult uint32
const (
RelationComparisonResultNone RelationComparisonResult = 0
RelationComparisonResultSucceeded RelationComparisonResult = 1 << 0
RelationComparisonResultFailed RelationComparisonResult = 1 << 1
RelationComparisonResultReportsUnmeasurable RelationComparisonResult = 1 << 3
RelationComparisonResultReportsUnreliable RelationComparisonResult = 1 << 4
RelationComparisonResultComplexityOverflow RelationComparisonResult = 1 << 5
RelationComparisonResultStackDepthOverflow RelationComparisonResult = 1 << 6
RelationComparisonResultReportsMask = RelationComparisonResultReportsUnmeasurable | RelationComparisonResultReportsUnreliable
RelationComparisonResultOverflow = RelationComparisonResultComplexityOverflow | RelationComparisonResultStackDepthOverflow
)
type DiagnosticAndArguments struct {
message *diagnostics.Message
arguments []any
}
type ErrorOutputContainer struct {
errors []*ast.Diagnostic
skipLogging bool
}
type ErrorReporter func(message *diagnostics.Message, args ...any)
type RecursionIdKind uint32
const (
RecursionIdKindNode RecursionIdKind = iota
RecursionIdKindSymbol
RecursionIdKindType
)
type RecursionId struct {
kind RecursionIdKind
id uint32
}
type Relation struct {
results map[string]RelationComparisonResult
}
func (r *Relation) get(key string) RelationComparisonResult {
return r.results[key]
}
func (r *Relation) set(key string, result RelationComparisonResult) {
if r.results == nil {
r.results = make(map[string]RelationComparisonResult)
}
r.results[key] = result
}
func (r *Relation) size() int {
return len(r.results)
}
func (c *Checker) isTypeIdenticalTo(source *Type, target *Type) bool {
return c.isTypeRelatedTo(source, target, c.identityRelation)
}
func (c *Checker) compareTypesIdentical(source *Type, target *Type) Ternary {
if c.isTypeRelatedTo(source, target, c.identityRelation) {
return TernaryTrue
}
return TernaryFalse
}
func (c *Checker) compareTypesAssignableSimple(source *Type, target *Type) Ternary {
if c.isTypeRelatedTo(source, target, c.assignableRelation) {
return TernaryTrue
}
return TernaryFalse
}
func (c *Checker) compareTypesAssignable(source *Type, target *Type, reportErrors bool) Ternary {
if c.isTypeRelatedTo(source, target, c.assignableRelation) {
return TernaryTrue
}
return TernaryFalse
}
func (c *Checker) compareTypesSubtypeOf(source *Type, target *Type) Ternary {
if c.isTypeRelatedTo(source, target, c.subtypeRelation) {
return TernaryTrue
}
return TernaryFalse
}
func (c *Checker) isTypeAssignableTo(source *Type, target *Type) bool {
return c.isTypeRelatedTo(source, target, c.assignableRelation)
}
func (c *Checker) isTypeSubtypeOf(source *Type, target *Type) bool {
return c.isTypeRelatedTo(source, target, c.subtypeRelation)
}
func (c *Checker) isTypeStrictSubtypeOf(source *Type, target *Type) bool {
return c.isTypeRelatedTo(source, target, c.strictSubtypeRelation)
}
func (c *Checker) isTypeComparableTo(source *Type, target *Type) bool {
return c.isTypeRelatedTo(source, target, c.comparableRelation)
}
func (c *Checker) areTypesComparable(type1 *Type, type2 *Type) bool {
return c.isTypeComparableTo(type1, type2) || c.isTypeComparableTo(type2, type1)
}
func (c *Checker) isTypeRelatedTo(source *Type, target *Type, relation *Relation) bool {
if isFreshLiteralType(source) {
source = source.AsLiteralType().regularType
}
if isFreshLiteralType(target) {
target = target.AsLiteralType().regularType
}
if source == target {
return true
}
if relation != c.identityRelation {
if relation == c.comparableRelation && target.flags&TypeFlagsNever == 0 && c.isSimpleTypeRelatedTo(target, source, relation, nil) || c.isSimpleTypeRelatedTo(source, target, relation, nil) {
return true
}
} else if !((source.flags|target.flags)&(TypeFlagsUnionOrIntersection|TypeFlagsIndexedAccess|TypeFlagsConditional|TypeFlagsSubstitution) != 0) {
// We have excluded types that may simplify to other forms, so types must have identical flags
if source.flags != target.flags {
return false
}
if source.flags&TypeFlagsSingleton != 0 {
return true
}
}
if source.flags&TypeFlagsObject != 0 && target.flags&TypeFlagsObject != 0 {
related := relation.get(getRelationKey(source, target, IntersectionStateNone, relation == c.identityRelation, false))
if related != RelationComparisonResultNone {
return related&RelationComparisonResultSucceeded != 0
}
}
if source.flags&TypeFlagsStructuredOrInstantiable != 0 || target.flags&TypeFlagsStructuredOrInstantiable != 0 {
return c.checkTypeRelatedTo(source, target, relation, nil /*errorNode*/)
}
return false
}
func (c *Checker) isSimpleTypeRelatedTo(source *Type, target *Type, relation *Relation, errorReporter ErrorReporter) bool {
s := source.flags
t := target.flags
if t&TypeFlagsAny != 0 || s&TypeFlagsNever != 0 || source == c.wildcardType {
return true
}
if t&TypeFlagsUnknown != 0 && !(relation == c.strictSubtypeRelation && s&TypeFlagsAny != 0) {
return true
}
if t&TypeFlagsNever != 0 {
return false
}
if s&TypeFlagsStringLike != 0 && t&TypeFlagsString != 0 {
return true
}
if s&TypeFlagsStringLiteral != 0 && s&TypeFlagsEnumLiteral != 0 && t&TypeFlagsStringLiteral != 0 && t&TypeFlagsEnumLiteral == 0 && source.AsLiteralType().value == target.AsLiteralType().value {
return true
}
if s&TypeFlagsNumberLike != 0 && t&TypeFlagsNumber != 0 {
return true
}
if s&TypeFlagsNumberLiteral != 0 && s&TypeFlagsEnumLiteral != 0 && t&TypeFlagsNumberLiteral != 0 && t&TypeFlagsEnumLiteral == 0 && source.AsLiteralType().value == target.AsLiteralType().value {
return true
}
if s&TypeFlagsBigIntLike != 0 && t&TypeFlagsBigInt != 0 {
return true
}
if s&TypeFlagsBooleanLike != 0 && t&TypeFlagsBoolean != 0 {
return true
}
if s&TypeFlagsESSymbolLike != 0 && t&TypeFlagsESSymbol != 0 {
return true
}
if s&TypeFlagsEnum != 0 && t&TypeFlagsEnum != 0 && source.symbol.Name == target.symbol.Name && c.isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter) {
return true
}
if s&TypeFlagsEnumLiteral != 0 && t&TypeFlagsEnumLiteral != 0 {
if s&TypeFlagsUnion != 0 && t&TypeFlagsUnion != 0 && c.isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter) {
return true
}
if s&TypeFlagsLiteral != 0 && t&TypeFlagsLiteral != 0 && source.AsLiteralType().value == target.AsLiteralType().value && c.isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter) {
return true
}
}
// In non-strictNullChecks mode, `undefined` and `null` are assignable to anything except `never`.
// Since unions and intersections may reduce to `never`, we exclude them here.
if s&TypeFlagsUndefined != 0 && (!c.strictNullChecks && t&TypeFlagsUnionOrIntersection == 0 || t&(TypeFlagsUndefined|TypeFlagsVoid) != 0) {
return true
}
if s&TypeFlagsNull != 0 && (!c.strictNullChecks && t&TypeFlagsUnionOrIntersection == 0 || t&TypeFlagsNull != 0) {
return true
}
if s&TypeFlagsObject != 0 && t&TypeFlagsNonPrimitive != 0 && !(relation == c.strictSubtypeRelation && c.isEmptyAnonymousObjectType(source) && source.objectFlags&ObjectFlagsFreshLiteral == 0) {
return true
}
if relation == c.assignableRelation || relation == c.comparableRelation {
if s&TypeFlagsAny != 0 {
return true
}
// Type number is assignable to any computed numeric enum type or any numeric enum literal type, and
// a numeric literal type is assignable any computed numeric enum type or any numeric enum literal type
// with a matching value. These rules exist such that enums can be used for bit-flag purposes.
if s&TypeFlagsNumber != 0 && (t&TypeFlagsEnum != 0 || t&TypeFlagsNumberLiteral != 0 && t&TypeFlagsEnumLiteral != 0) {
return true
}
if s&TypeFlagsNumberLiteral != 0 && s&TypeFlagsEnumLiteral == 0 && (t&TypeFlagsEnum != 0 || t&TypeFlagsNumberLiteral != 0 && t&TypeFlagsEnumLiteral != 0 && source.AsLiteralType().value == target.AsLiteralType().value) {
return true
}
// Anything is assignable to a union containing undefined, null, and {}
if c.isUnknownLikeUnionType(target) {
return true
}
}
return false
}
func (c *Checker) isEnumTypeRelatedTo(source *ast.Symbol, target *ast.Symbol, errorReporter ErrorReporter) bool {
sourceSymbol := core.IfElse(source.Flags&ast.SymbolFlagsEnumMember != 0, c.getParentOfSymbol(source), source)
targetSymbol := core.IfElse(target.Flags&ast.SymbolFlagsEnumMember != 0, c.getParentOfSymbol(target), target)
if sourceSymbol == targetSymbol {
return true
}
if sourceSymbol.Name != targetSymbol.Name || sourceSymbol.Flags&ast.SymbolFlagsRegularEnum == 0 || targetSymbol.Flags&ast.SymbolFlagsRegularEnum == 0 {
return false
}
key := EnumRelationKey{sourceId: ast.GetSymbolId(sourceSymbol), targetId: ast.GetSymbolId(targetSymbol)}
if entry := c.enumRelation[key]; entry != RelationComparisonResultNone && !(entry&RelationComparisonResultFailed != 0 && errorReporter != nil) {
return entry&RelationComparisonResultSucceeded != 0
}
targetEnumType := c.getTypeOfSymbol(targetSymbol)
for _, sourceProperty := range c.getPropertiesOfType(c.getTypeOfSymbol(sourceSymbol)) {
if sourceProperty.Flags&ast.SymbolFlagsEnumMember != 0 {
targetProperty := c.getPropertyOfType(targetEnumType, sourceProperty.Name)
if targetProperty == nil || targetProperty.Flags&ast.SymbolFlagsEnumMember == 0 {
if errorReporter != nil {
errorReporter(diagnostics.Property_0_is_missing_in_type_1, c.symbolToString(sourceProperty), c.TypeToString(c.getDeclaredTypeOfSymbol(targetSymbol)))
}
c.enumRelation[key] = RelationComparisonResultFailed
return false
}
sourceValue := c.getEnumMemberValue(ast.GetDeclarationOfKind(sourceProperty, ast.KindEnumMember)).Value
targetValue := c.getEnumMemberValue(ast.GetDeclarationOfKind(targetProperty, ast.KindEnumMember)).Value
if sourceValue != targetValue {
// If we have 2 enums with *known* values that differ, they are incompatible.
if sourceValue != nil && targetValue != nil {
if errorReporter != nil {
errorReporter(diagnostics.Each_declaration_of_0_1_differs_in_its_value_where_2_was_expected_but_3_was_given, c.symbolToString(targetSymbol), c.symbolToString(targetProperty), c.valueToString(targetValue), c.valueToString(sourceValue))
}
c.enumRelation[key] = RelationComparisonResultFailed
return false
}
// At this point we know that at least one of the values is 'undefined'.
// This may mean that we have an opaque member from an ambient enum declaration,
// or that we were not able to calculate it (which is basically an error).
//
// Either way, we can assume that it's numeric.
// If the other is a string, we have a mismatch in types.
_, sourceIsString := sourceValue.(string)
_, targetIsString := targetValue.(string)
if sourceIsString || targetIsString {
if errorReporter != nil {
knownStringValue := core.OrElse(sourceValue, targetValue)
errorReporter(diagnostics.One_value_of_0_1_is_the_string_2_and_the_other_is_assumed_to_be_an_unknown_numeric_value, c.symbolToString(targetSymbol), c.symbolToString(targetProperty), c.valueToString(knownStringValue))
}
c.enumRelation[key] = RelationComparisonResultFailed
return false
}
}
}
}
c.enumRelation[key] = RelationComparisonResultSucceeded
return true
}
func (c *Checker) checkTypeAssignableTo(source *Type, target *Type, errorNode *ast.Node, headMessage *diagnostics.Message) bool {
return c.checkTypeRelatedToEx(source, target, c.assignableRelation, errorNode, headMessage, nil)
}
func (c *Checker) checkTypeAssignableToEx(source *Type, target *Type, errorNode *ast.Node, headMessage *diagnostics.Message, diagnosticOutput *[]*ast.Diagnostic) bool {
return c.checkTypeRelatedToEx(source, target, c.assignableRelation, errorNode, headMessage, diagnosticOutput)
}
func (c *Checker) checkTypeComparableTo(source *Type, target *Type, errorNode *ast.Node, headMessage *diagnostics.Message) bool {
return c.checkTypeRelatedToEx(source, target, c.comparableRelation, errorNode, headMessage, nil)
}
func (c *Checker) checkTypeRelatedTo(source *Type, target *Type, relation *Relation, errorNode *ast.Node) bool {
return c.checkTypeRelatedToEx(source, target, relation, errorNode, nil, nil)
}
// Check that source is related to target according to the given relation. When errorNode is non-nil, errors are
// reported to the checker's diagnostic collection or through diagnosticOutput when non-nil. Callers can assume that
// this function only reports zero or one error to diagnosticOutput (unlike checkTypeRelatedToAndOptionallyElaborate).
func (c *Checker) checkTypeRelatedToEx(
source *Type,
target *Type,
relation *Relation,
errorNode *ast.Node,
headMessage *diagnostics.Message,
diagnosticOutput *[]*ast.Diagnostic,
) bool {
r := c.getRelater()
r.relation = relation
r.errorNode = errorNode
r.relationCount = (16_000_000 - relation.size()) / 8
result := r.isRelatedToEx(source, target, RecursionFlagsBoth, errorNode != nil /*reportErrors*/, headMessage, IntersectionStateNone)
if r.overflow {
// Record this relation as having failed such that we don't attempt the overflowing operation again.
id := getRelationKey(source, target, IntersectionStateNone, relation == c.identityRelation, false /*ignoreConstraints*/)
relation.set(id, RelationComparisonResultFailed|core.IfElse(r.relationCount <= 0, RelationComparisonResultComplexityOverflow, RelationComparisonResultStackDepthOverflow))
message := core.IfElse(r.relationCount <= 0, diagnostics.Excessive_complexity_comparing_types_0_and_1, diagnostics.Excessive_stack_depth_comparing_types_0_and_1)
if errorNode == nil {
errorNode = c.currentNode
}
c.reportDiagnostic(NewDiagnosticForNode(errorNode, message, c.TypeToString(source), c.TypeToString(target)), diagnosticOutput)
} else if r.errorChain != nil {
// Check if we should issue an extra diagnostic to produce a quickfix for a slightly incorrect import statement
if headMessage != nil && errorNode != nil && result == TernaryFalse && source.symbol != nil && c.exportTypeLinks.Has(source.symbol) {
links := c.exportTypeLinks.Get(source.symbol)
if links.originatingImport != nil && !ast.IsImportCall(links.originatingImport) {
helpfulRetry := c.checkTypeRelatedTo(c.getTypeOfSymbol(links.target), target, relation /*errorNode*/, nil)
if helpfulRetry {
// Likely an incorrect import. Issue a helpful diagnostic to produce a quickfix to change the import
r.relatedInfo = append(r.relatedInfo, createDiagnosticForNode(links.originatingImport, diagnostics.Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_Consider_using_a_default_import_or_import_require_here_instead))
}
}
}
c.reportDiagnostic(createDiagnosticChainFromErrorChain(r.errorChain, r.errorNode, r.relatedInfo), diagnosticOutput)
}
c.putRelater(r)
return result != TernaryFalse
}
func createDiagnosticChainFromErrorChain(chain *ErrorChain, errorNode *ast.Node, relatedInfo []*ast.Diagnostic) *ast.Diagnostic {
for chain != nil && chain.message.ElidedInCompatibilityPyramid() {
chain = chain.next
}
if chain == nil {
return nil
}
next := createDiagnosticChainFromErrorChain(chain.next, errorNode, relatedInfo)
if next == nil {
return NewDiagnosticForNode(errorNode, chain.message, chain.args...).SetRelatedInfo(relatedInfo)
}
return ast.NewDiagnosticChain(next, chain.message, chain.args...)
}
func (c *Checker) reportDiagnostic(diagnostic *ast.Diagnostic, diagnosticOutput *[]*ast.Diagnostic) {
if diagnostic != nil {
if diagnosticOutput != nil {
*diagnosticOutput = append(*diagnosticOutput, diagnostic)
} else {
c.diagnostics.Add(diagnostic)
}
}
}
func (c *Checker) checkTypeAssignableToAndOptionallyElaborate(source *Type, target *Type, errorNode *ast.Node, expr *ast.Node, headMessage *diagnostics.Message, diagnosticOutput *[]*ast.Diagnostic) bool {
return c.checkTypeRelatedToAndOptionallyElaborate(source, target, c.assignableRelation, errorNode, expr, headMessage, diagnosticOutput)
}
func (c *Checker) checkTypeRelatedToAndOptionallyElaborate(source *Type, target *Type, relation *Relation, errorNode *ast.Node, expr *ast.Node, headMessage *diagnostics.Message, diagnosticOutput *[]*ast.Diagnostic) bool {
if c.isTypeRelatedTo(source, target, relation) {
return true
}
if errorNode != nil && !c.elaborateError(expr, source, target, relation, headMessage, diagnosticOutput) {
return c.checkTypeRelatedToEx(source, target, relation, errorNode, headMessage, diagnosticOutput)
}
return false
}
func (c *Checker) elaborateError(node *ast.Node, source *Type, target *Type, relation *Relation, headMessage *diagnostics.Message, diagnosticOutput *[]*ast.Diagnostic) bool {
if node == nil || c.isOrHasGenericConditional(target) {
return false
}
if c.elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, SignatureKindConstruct, headMessage, diagnosticOutput) ||
c.elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, SignatureKindCall, headMessage, diagnosticOutput) {
return true
}
switch node.Kind {
case ast.KindAsExpression:
if !isConstAssertion(node) {
break
}
fallthrough
case ast.KindJsxExpression, ast.KindParenthesizedExpression:
return c.elaborateError(node.Expression(), source, target, relation, headMessage, diagnosticOutput)
case ast.KindBinaryExpression:
switch node.AsBinaryExpression().OperatorToken.Kind {
case ast.KindEqualsToken, ast.KindCommaToken:
return c.elaborateError(node.AsBinaryExpression().Right, source, target, relation, headMessage, diagnosticOutput)
}
case ast.KindObjectLiteralExpression:
return c.elaborateObjectLiteral(node, source, target, relation, diagnosticOutput)
case ast.KindArrayLiteralExpression:
return c.elaborateArrayLiteral(node, source, target, relation, diagnosticOutput)
case ast.KindArrowFunction:
return c.elaborateArrowFunction(node, source, target, relation, diagnosticOutput)
case ast.KindJsxAttributes:
return c.elaborateJsxComponents(node, source, target, relation, diagnosticOutput)
}
return false
}
func (c *Checker) isOrHasGenericConditional(t *Type) bool {
return t.flags&TypeFlagsConditional != 0 || (t.flags&TypeFlagsIntersection != 0 && core.Some(t.Types(), c.isOrHasGenericConditional))
}
func (c *Checker) elaborateDidYouMeanToCallOrConstruct(node *ast.Node, source *Type, target *Type, relation *Relation, kind SignatureKind, headMessage *diagnostics.Message, diagnosticOutput *[]*ast.Diagnostic) bool {
if core.Some(c.getSignaturesOfType(source, kind), func(s *Signature) bool {
returnType := c.getReturnTypeOfSignature(s)
return returnType.flags&(TypeFlagsAny|TypeFlagsNever) == 0 && c.checkTypeRelatedTo(returnType, target, relation, nil /*errorNode*/)
}) {
var diags []*ast.Diagnostic
if !c.checkTypeRelatedToEx(source, target, relation, node, headMessage, &diags) {
diagnostic := diags[0]
message := core.IfElse(kind == SignatureKindConstruct,
diagnostics.Did_you_mean_to_use_new_with_this_expression,
diagnostics.Did_you_mean_to_call_this_expression)
c.reportDiagnostic(diagnostic.AddRelatedInfo(createDiagnosticForNode(node, message)), diagnosticOutput)
return true
}
}
return false
}
func (c *Checker) elaborateObjectLiteral(node *ast.Node, source *Type, target *Type, relation *Relation, diagnosticOutput *[]*ast.Diagnostic) bool {
if target.flags&(TypeFlagsPrimitive|TypeFlagsNever) != 0 {
return false
}
reportedError := false
for _, prop := range node.AsObjectLiteralExpression().Properties.Nodes {
if ast.IsSpreadAssignment(prop) {
continue
}
nameType := c.getLiteralTypeFromProperty(c.getSymbolOfDeclaration(prop), TypeFlagsStringOrNumberLiteralOrUnique, false)
if nameType == nil || nameType.flags&TypeFlagsNever != 0 {
continue
}
switch prop.Kind {
case ast.KindSetAccessor, ast.KindGetAccessor, ast.KindMethodDeclaration, ast.KindShorthandPropertyAssignment:
reportedError = c.elaborateElement(source, target, relation, prop.Name(), nil, nameType, nil, diagnosticOutput) || reportedError
case ast.KindPropertyAssignment:
message := core.IfElse(ast.IsComputedNonLiteralName(prop.Name()), diagnostics.Type_of_computed_property_s_value_is_0_which_is_not_assignable_to_type_1, nil)
reportedError = c.elaborateElement(source, target, relation, prop.Name(), prop.Initializer(), nameType, message, diagnosticOutput) || reportedError
}
}
return reportedError
}
func (c *Checker) elaborateArrayLiteral(node *ast.Node, source *Type, target *Type, relation *Relation, diagnosticOutput *[]*ast.Diagnostic) bool {
if target.flags&(TypeFlagsPrimitive|TypeFlagsNever) != 0 {
return false
}
if !c.isTupleLikeType(source) {
c.pushContextualType(node, target, false /*isCache*/)
source = c.checkArrayLiteral(node, CheckModeContextual|CheckModeForceTuple)
c.popContextualType()
if !c.isTupleLikeType(source) {
return false
}
}
reportedError := false
for i, element := range node.AsArrayLiteralExpression().Elements.Nodes {
if ast.IsOmittedExpression(element) || c.isTupleLikeType(target) && c.getPropertyOfType(target, jsnum.Number(i).String()) == nil {
continue
}
nameType := c.getNumberLiteralType(jsnum.Number(i))
checkNode := c.getEffectiveCheckNode(element)
reportedError = c.elaborateElement(source, target, relation, checkNode, checkNode, nameType, nil, diagnosticOutput) || reportedError
}
return reportedError
}
func (c *Checker) elaborateElement(source *Type, target *Type, relation *Relation, prop *ast.Node, next *ast.Node, nameType *Type, errorMessage *diagnostics.Message, diagnosticOutput *[]*ast.Diagnostic) bool {
targetPropType := c.getBestMatchIndexedAccessTypeOrUndefined(source, target, nameType)
if targetPropType == nil || targetPropType.flags&TypeFlagsIndexedAccess != 0 {
// Don't elaborate on indexes on generic variables
return false
}
sourcePropType := c.getIndexedAccessTypeOrUndefined(source, nameType, AccessFlagsNone, nil, nil)
if sourcePropType == nil || c.checkTypeRelatedTo(sourcePropType, targetPropType, relation, nil /*errorNode*/) {
// Don't elaborate on indexes on generic variables or when types match
return false
}
if next != nil && c.elaborateError(next, sourcePropType, targetPropType, relation, nil /*headMessage*/, diagnosticOutput) {
return true
}
// Issue error on the prop itself, since the prop couldn't elaborate the error
var diags []*ast.Diagnostic
// Use the expression type, if available
specificSource := sourcePropType
if next != nil {
specificSource = c.checkExpressionForMutableLocationWithContextualType(next, sourcePropType)
}
if c.exactOptionalPropertyTypes && c.isExactOptionalPropertyMismatch(specificSource, targetPropType) {
diags = append(diags, createDiagnosticForNode(prop, diagnostics.Type_0_is_not_assignable_to_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefined_to_the_type_of_the_target, c.TypeToString(specificSource), c.TypeToString(targetPropType)))
} else {
propName := c.getPropertyNameFromIndex(nameType, nil /*accessNode*/)
targetIsOptional := core.OrElse(c.getPropertyOfType(target, propName), c.unknownSymbol).Flags&ast.SymbolFlagsOptional != 0
sourceIsOptional := core.OrElse(c.getPropertyOfType(source, propName), c.unknownSymbol).Flags&ast.SymbolFlagsOptional != 0
targetPropType = c.removeMissingType(targetPropType, targetIsOptional)
sourcePropType = c.removeMissingType(sourcePropType, targetIsOptional && sourceIsOptional)
result := c.checkTypeRelatedToEx(specificSource, targetPropType, relation, prop, errorMessage, &diags)
if result && specificSource != sourcePropType {
// If for whatever reason the expression type doesn't yield an error, make sure we still issue an error on the sourcePropType
c.checkTypeRelatedToEx(sourcePropType, targetPropType, relation, prop, errorMessage, &diags)
}
}
if len(diags) == 0 {
return false
}
diagnostic := diags[0]
var propertyName string
var targetProp *ast.Symbol
if isTypeUsableAsPropertyName(nameType) {
propertyName = getPropertyNameFromType(nameType)
targetProp = c.getPropertyOfType(target, propertyName)
}
issuedElaboration := false
if targetProp == nil {
indexInfo := c.getApplicableIndexInfo(target, nameType)
if indexInfo != nil && indexInfo.declaration != nil && !ast.GetSourceFileOfNode(indexInfo.declaration).HasNoDefaultLib {
issuedElaboration = true
diagnostic.AddRelatedInfo(createDiagnosticForNode(indexInfo.declaration, diagnostics.The_expected_type_comes_from_this_index_signature))
}
}
if !issuedElaboration && (targetProp != nil && len(targetProp.Declarations) != 0 || target.symbol != nil && len(target.symbol.Declarations) != 0) {
var targetNode *ast.Node
if targetProp != nil && len(targetProp.Declarations) != 0 {
targetNode = targetProp.Declarations[0]
} else {
targetNode = target.symbol.Declarations[0]
}
if propertyName == "" || nameType.flags&TypeFlagsUniqueESSymbol != 0 {
propertyName = c.TypeToString(nameType)
}
if !ast.GetSourceFileOfNode(targetNode).HasNoDefaultLib {
diagnostic.AddRelatedInfo(createDiagnosticForNode(targetNode, diagnostics.The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1, propertyName, c.TypeToString(target)))
}
}
c.reportDiagnostic(diagnostic, diagnosticOutput)
return true
}
func (c *Checker) getBestMatchIndexedAccessTypeOrUndefined(source *Type, target *Type, nameType *Type) *Type {
idx := c.getIndexedAccessTypeOrUndefined(target, nameType, AccessFlagsNone, nil, nil)
if idx != nil {
return idx
}
if target.flags&TypeFlagsUnion != 0 {
best := c.getBestMatchingType(source, target, c.compareTypesAssignableSimple)
if best != nil {
return c.getIndexedAccessTypeOrUndefined(best, nameType, AccessFlagsNone, nil, nil)
}
}
return nil
}
func (c *Checker) checkExpressionForMutableLocationWithContextualType(next *ast.Node, sourcePropType *Type) *Type {
c.pushContextualType(next, sourcePropType, false /*isCache*/)
result := c.checkExpressionForMutableLocation(next, CheckModeContextual)
c.popContextualType()
return result
}
func (c *Checker) elaborateArrowFunction(node *ast.Node, source *Type, target *Type, relation *Relation, diagnosticOutput *[]*ast.Diagnostic) bool {
// Don't elaborate blocks or functions with annotated parameter types
if ast.IsBlock(node.Body()) || core.Some(node.Parameters(), hasType) {
return false
}
sourceSig := c.getSingleCallSignature(source)
if sourceSig == nil {
return false
}
targetSignatures := c.getSignaturesOfType(target, SignatureKindCall)
if len(targetSignatures) == 0 {
return false
}
returnExpression := node.Body()
sourceReturn := c.getReturnTypeOfSignature(sourceSig)
targetReturn := c.getUnionType(core.Map(targetSignatures, c.getReturnTypeOfSignature))
if c.checkTypeRelatedTo(sourceReturn, targetReturn, relation, nil /*errorNode*/) {
return false
}
if returnExpression != nil && c.elaborateError(returnExpression, sourceReturn, targetReturn, relation, nil /*headMessage*/, diagnosticOutput) {
return true
}
var diags []*ast.Diagnostic
c.checkTypeRelatedToEx(sourceReturn, targetReturn, relation, returnExpression, nil /*headMessage*/, &diags)
if len(diags) != 0 {
diagnostic := diags[0]
if target.symbol != nil && len(target.symbol.Declarations) != 0 {
diagnostic.AddRelatedInfo(createDiagnosticForNode(target.symbol.Declarations[0], diagnostics.The_expected_type_comes_from_the_return_type_of_this_signature))
}
if getFunctionFlags(node)&FunctionFlagsAsync == 0 && c.getTypeOfPropertyOfType(sourceReturn, "then") == nil && c.checkTypeRelatedTo(c.createPromiseType(sourceReturn), targetReturn, relation, nil /*errorNode*/) {
diagnostic.AddRelatedInfo(createDiagnosticForNode(node, diagnostics.Did_you_mean_to_mark_this_function_as_async))
}
c.reportDiagnostic(diagnostic, diagnosticOutput)
return true
}
return false
}
// A type is 'weak' if it is an object type with at least one optional property
// and no required properties, call/construct signatures or index signatures
func (c *Checker) isWeakType(t *Type) bool {
if t.flags&TypeFlagsObject != 0 {
resolved := c.resolveStructuredTypeMembers(t)
return len(resolved.signatures) == 0 && len(resolved.indexInfos) == 0 && len(resolved.properties) > 0 && core.Every(resolved.properties, func(p *ast.Symbol) bool {
return p.Flags&ast.SymbolFlagsOptional != 0
})
}
if t.flags&TypeFlagsSubstitution != 0 {
return c.isWeakType(t.AsSubstitutionType().baseType)
}
if t.flags&TypeFlagsIntersection != 0 {
return core.Every(t.Types(), c.isWeakType)
}
return false
}
func (c *Checker) hasCommonProperties(source *Type, target *Type, isComparingJsxAttributes bool) bool {
for _, prop := range c.getPropertiesOfType(source) {
if c.isKnownProperty(target, prop.Name, isComparingJsxAttributes) {
return true
}
}
return false
}
/**
* Check if a property with the given name is known anywhere in the given type. In an object type, a property
* is considered known if
* 1. the object type is empty and the check is for assignability, or
* 2. if the object type has index signatures, or
* 3. if the property is actually declared in the object type
* (this means that 'toString', for example, is not usually a known property).
* 4. In a union or intersection type,
* a property is considered known if it is known in any constituent type.
* @param targetType a type to search a given name in
* @param name a property name to search
* @param isComparingJsxAttributes a boolean flag indicating whether we are searching in JsxAttributesType
*/
func (c *Checker) isKnownProperty(targetType *Type, name string, isComparingJsxAttributes bool) bool {
if targetType.flags&TypeFlagsObject != 0 {
// For backwards compatibility a symbol-named property is satisfied by a string index signature. This
// is incorrect and inconsistent with element access expressions, where it is an error, so eventually
// we should remove this exception.
if c.getPropertyOfObjectType(targetType, name) != nil ||
c.getApplicableIndexInfoForName(targetType, name) != nil ||
isLateBoundName(name) && c.getIndexInfoOfType(targetType, c.stringType) != nil ||
isComparingJsxAttributes && isHyphenatedJsxName(name) {
// For JSXAttributes, if the attribute has a hyphenated name, consider that the attribute to be known.
return true
}
}
if targetType.flags&TypeFlagsSubstitution != 0 {
return c.isKnownProperty(targetType.AsSubstitutionType().baseType, name, isComparingJsxAttributes)
}
if targetType.flags&TypeFlagsUnionOrIntersection != 0 && isExcessPropertyCheckTarget(targetType) {
for _, t := range targetType.Types() {
if c.isKnownProperty(t, name, isComparingJsxAttributes) {
return true
}
}
}
return false
}
func isHyphenatedJsxName(name string) bool {
return strings.Contains(name, "-")
}
func isExcessPropertyCheckTarget(t *Type) bool {
return t.flags&TypeFlagsObject != 0 && t.objectFlags&ObjectFlagsObjectLiteralPatternWithComputedProperties == 0 ||
t.flags&TypeFlagsNonPrimitive != 0 ||
t.flags&TypeFlagsSubstitution != 0 && isExcessPropertyCheckTarget(t.AsSubstitutionType().baseType) ||
t.flags&TypeFlagsUnion != 0 && core.Some(t.Types(), isExcessPropertyCheckTarget) ||
t.flags&TypeFlagsIntersection != 0 && core.Every(t.Types(), isExcessPropertyCheckTarget)
}
// Return true if the given type is deeply nested. We consider this to be the case when the given stack contains
// maxDepth or more occurrences of types with the same recursion identity as the given type. The recursion identity
// provides a shared identity for type instantiations that repeat in some (possibly infinite) pattern. For example,
// in `type Deep<T> = { next: Deep<Deep<T>> }`, repeatedly referencing the `next` property leads to an infinite
// sequence of ever deeper instantiations with the same recursion identity (in this case the symbol associated with
// the object type literal).
// A homomorphic mapped type is considered deeply nested if its target type is deeply nested, and an intersection is
// considered deeply nested if any constituent of the intersection is deeply nested.
// It is possible, though highly unlikely, for the deeply nested check to be true in a situation where a chain of
// instantiations is not infinitely expanding. Effectively, we will generate a false positive when two types are
// structurally equal to at least maxDepth levels, but unequal at some level beyond that.
func (c *Checker) isDeeplyNestedType(t *Type, stack []*Type, maxDepth int) bool {
if len(stack) >= maxDepth {
if t.objectFlags&ObjectFlagsInstantiatedMapped == ObjectFlagsInstantiatedMapped {
t = c.getMappedTargetWithSymbol(t)
}
if t.flags&TypeFlagsIntersection != 0 {
for _, t := range t.Types() {
if c.isDeeplyNestedType(t, stack, maxDepth) {
return true
}
}
}
identity := getRecursionIdentity(t)
count := 0
lastTypeId := TypeId(0)
for _, t := range stack {
if c.hasMatchingRecursionIdentity(t, identity) {
// We only count occurrences with a higher type id than the previous occurrence, since higher
// type ids are an indicator of newer instantiations caused by recursion.
if t.id >= lastTypeId {
count++
if count >= maxDepth {
return true
}
}
lastTypeId = t.id
}
}
}
return false
}
// Unwrap nested homomorphic mapped types and return the deepest target type that has a symbol. This better
// preserves unique type identities for mapped types applied to explicitly written object literals. For example
// in `Mapped<{ x: Mapped<{ x: Mapped<{ x: string }>}>}>`, each of the mapped type applications will have a
// unique recursion identity (that of their target object type literal) and thus avoid appearing deeply nested.
func (c *Checker) getMappedTargetWithSymbol(t *Type) *Type {
for {
if t.objectFlags&ObjectFlagsInstantiatedMapped == ObjectFlagsInstantiatedMapped {
target := c.getModifiersTypeFromMappedType(t)
if target != nil && (target.symbol != nil || target.flags&TypeFlagsIntersection != 0 &&
core.Some(target.Types(), func(t *Type) bool { return t.symbol != nil })) {
t = target
continue
}
}
return t
}
}
func (c *Checker) hasMatchingRecursionIdentity(t *Type, identity RecursionId) bool {
if t.objectFlags&ObjectFlagsInstantiatedMapped == ObjectFlagsInstantiatedMapped {
t = c.getMappedTargetWithSymbol(t)
}
if t.flags&TypeFlagsIntersection != 0 {
for _, t := range t.Types() {
if c.hasMatchingRecursionIdentity(t, identity) {
return true
}
}
return false
}
return getRecursionIdentity(t) == identity
}
// The recursion identity of a type is an object identity that is shared among multiple instantiations of the type.
// We track recursion identities in order to identify deeply nested and possibly infinite type instantiations with
// the same origin. For example, when type parameters are in scope in an object type such as { x: T }, all
// instantiations of that type have the same recursion identity. The default recursion identity is the object
// identity of the type, meaning that every type is unique. Generally, types with constituents that could circularly
// reference the type have a recursion identity that differs from the object identity.
func getRecursionIdentity(t *Type) RecursionId {
// Object and array literals are known not to contain recursive references and don't need a recursion identity.
if t.flags&TypeFlagsObject != 0 && !isObjectOrArrayLiteralType(t) {
if t.objectFlags&ObjectFlagsReference != 0 && t.AsTypeReference().node != nil {
// Deferred type references are tracked through their associated AST node. This gives us finer
// granularity than using their associated target because each manifest type reference has a
// unique AST node.
return RecursionId{kind: RecursionIdKindNode, id: uint32(ast.GetNodeId(t.AsTypeReference().node))}
}
if t.symbol != nil && !(t.objectFlags&ObjectFlagsAnonymous != 0 && t.symbol.Flags&ast.SymbolFlagsClass != 0) {
// We track object types that have a symbol by that symbol (representing the origin of the type), but
// exclude the static side of a class since it shares its symbol with the instance side.
return RecursionId{kind: RecursionIdKindSymbol, id: uint32(ast.GetSymbolId(t.symbol))}
}
if isTupleType(t) {
return RecursionId{kind: RecursionIdKindType, id: uint32(t.Target().id)}
}
}
if t.flags&TypeFlagsTypeParameter != 0 && t.symbol != nil {
// We use the symbol of the type parameter such that all "fresh" instantiations of that type parameter
// have the same recursion identity.
return RecursionId{kind: RecursionIdKindSymbol, id: uint32(ast.GetSymbolId(t.symbol))}
}
if t.flags&TypeFlagsIndexedAccess != 0 {
// Identity is the leftmost object type in a chain of indexed accesses, eg, in A[P1][P2][P3] it is A.
t = t.AsIndexedAccessType().objectType
for t.flags&TypeFlagsIndexedAccess != 0 {
t = t.AsIndexedAccessType().objectType
}
return RecursionId{kind: RecursionIdKindType, id: uint32(t.id)}
}
if t.flags&TypeFlagsConditional != 0 {
// The root object represents the origin of the conditional type
return RecursionId{kind: RecursionIdKindNode, id: uint32(ast.GetNodeId(t.AsConditionalType().root.node.AsNode()))}
}
return RecursionId{kind: RecursionIdKindType, id: uint32(t.id)}
}
func (c *Checker) getBestMatchingType(source *Type, target *Type, isRelatedTo func(source *Type, target *Type) Ternary) *Type {
if t := c.findMatchingDiscriminantType(source, target, isRelatedTo); t != nil {
return t
}
if t := c.findMatchingTypeReferenceOrTypeAliasReference(source, target); t != nil {
return t
}
if t := c.findBestTypeForObjectLiteral(source, target); t != nil {
return t
}
if t := c.findBestTypeForInvokable(source, target, SignatureKindCall); t != nil {
return t
}
if t := c.findBestTypeForInvokable(source, target, SignatureKindConstruct); t != nil {
return t
}
return c.findMostOverlappyType(source, target)
}
func (c *Checker) findMatchingTypeReferenceOrTypeAliasReference(source *Type, unionTarget *Type) *Type {
sourceObjectFlags := source.objectFlags
if sourceObjectFlags&(ObjectFlagsReference|ObjectFlagsAnonymous) != 0 && unionTarget.flags&TypeFlagsUnion != 0 {
for _, target := range unionTarget.Types() {
if target.flags&TypeFlagsObject != 0 {
overlapObjFlags := sourceObjectFlags & target.objectFlags
if overlapObjFlags&ObjectFlagsReference != 0 && source.Target() == target.Target() {
return target
}
if overlapObjFlags&ObjectFlagsAnonymous != 0 && source.alias != nil && target.alias != nil && source.alias.symbol == target.alias.symbol {
return target
}
}
}
}
return nil
}
func (c *Checker) findBestTypeForInvokable(source *Type, unionTarget *Type, kind SignatureKind) *Type {
if len(c.getSignaturesOfType(source, kind)) != 0 {
return core.Find(unionTarget.Types(), func(t *Type) bool { return len(c.getSignaturesOfType(t, kind)) != 0 })
}
return nil
}
func (c *Checker) findMostOverlappyType(source *Type, unionTarget *Type) *Type {
var bestMatch *Type
if source.flags&(TypeFlagsPrimitive|TypeFlagsInstantiablePrimitive) == 0 {
matchingCount := 0
for _, target := range unionTarget.Types() {
if target.flags&(TypeFlagsPrimitive|TypeFlagsInstantiablePrimitive) == 0 {
overlap := c.getIntersectionType([]*Type{c.getIndexType(source), c.getIndexType(target)})
if overlap.flags&TypeFlagsIndex != 0 {
// perfect overlap of keys
return target
} else if isUnitType(overlap) || overlap.flags&TypeFlagsUnion != 0 {
// We only want to account for literal types otherwise.
// If we have a union of index types, it seems likely that we
// needed to elaborate between two generic mapped types anyway.
length := 1
if overlap.flags&TypeFlagsUnion != 0 {
length = core.CountWhere(overlap.Types(), isUnitType)
}
if length >= matchingCount {
bestMatch = target
matchingCount = length
}
}
}
}
}
return bestMatch
}
func (c *Checker) findBestTypeForObjectLiteral(source *Type, unionTarget *Type) *Type {
if source.objectFlags&ObjectFlagsObjectLiteral != 0 && someType(unionTarget, c.isArrayLikeType) {
return core.Find(unionTarget.Types(), func(t *Type) bool { return !c.isArrayLikeType(t) })
}
return nil
}
func (c *Checker) shouldReportUnmatchedPropertyError(source *Type, target *Type) bool {
typeCallSignatures := c.getSignaturesOfStructuredType(source, SignatureKindCall)
typeConstructSignatures := c.getSignaturesOfStructuredType(source, SignatureKindConstruct)
typeProperties := c.getPropertiesOfObjectType(source)
if (len(typeCallSignatures) != 0 || len(typeConstructSignatures) != 0) && len(typeProperties) == 0 {
if (len(c.getSignaturesOfType(target, SignatureKindCall)) != 0 && len(typeCallSignatures) != 0) ||
len(c.getSignaturesOfType(target, SignatureKindConstruct)) != 0 && len(typeConstructSignatures) != 0 {
// target has similar signature kinds to source, still focus on the unmatched property
return true
}
return false
}
return true
}
func (c *Checker) getUnmatchedProperty(source *Type, target *Type, requireOptionalProperties bool, matchDiscriminantProperties bool) *ast.Symbol {
return c.getUnmatchedPropertiesWorker(source, target, requireOptionalProperties, matchDiscriminantProperties, nil)
}
func (c *Checker) getUnmatchedProperties(source *Type, target *Type, requireOptionalProperties bool, matchDiscriminantProperties bool) []*ast.Symbol {
var props []*ast.Symbol
c.getUnmatchedPropertiesWorker(source, target, requireOptionalProperties, matchDiscriminantProperties, &props)
return props
}
func (c *Checker) getUnmatchedPropertiesWorker(source *Type, target *Type, requireOptionalProperties bool, matchDiscriminantProperties bool, propsOut *[]*ast.Symbol) *ast.Symbol {
properties := c.getPropertiesOfType(target)
for _, targetProp := range properties {
// TODO: remove this when we support static private identifier fields and find other solutions to get privateNamesAndStaticFields test to pass
if isStaticPrivateIdentifierProperty(targetProp) {
continue
}
if requireOptionalProperties || targetProp.Flags&ast.SymbolFlagsOptional == 0 && targetProp.CheckFlags&ast.CheckFlagsPartial == 0 {
sourceProp := c.getPropertyOfType(source, targetProp.Name)
if sourceProp == nil {
if propsOut == nil {
return targetProp
}
*propsOut = append(*propsOut, targetProp)
} else if matchDiscriminantProperties {
targetType := c.getTypeOfSymbol(targetProp)
if targetType.flags&TypeFlagsUnit != 0 {
sourceType := c.getTypeOfSymbol(sourceProp)
if !(sourceType.flags&TypeFlagsAny != 0 || c.getRegularTypeOfLiteralType(sourceType) == c.getRegularTypeOfLiteralType(targetType)) {
if propsOut == nil {
return targetProp
}
*propsOut = append(*propsOut, targetProp)
}
}
}
}