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
//! Object type subtype checking.
//!
//! This module handles subtyping for TypeScript's object types:
//! - Plain objects with named properties
//! - Objects with index signatures (string and number)
//! - Property compatibility (optional, readonly, type, `write_type`)
//! - **Rule #26**: Split Accessors (Getter/Setter Variance)
//! - Read types are covariant: source.read <: target.read
//! - Write types are contravariant: target.write <: source.write
//! - Readonly target properties only check read type (no write access)
//! - Private brand checking for nominal class typing
use crate::types::{ObjectFlags, ObjectShape, ObjectShapeId, PropertyInfo, TypeId, Visibility};
use crate::utils;
use tsz_common::interner::Atom;
use super::super::{SubtypeChecker, SubtypeResult, TypeResolver};
impl<'a, R: TypeResolver> SubtypeChecker<'a, R> {
/// Look up a property in a list of properties, using cached index if available.
pub(crate) fn lookup_property<'props>(
&self,
props: &'props [PropertyInfo],
shape_id: Option<ObjectShapeId>,
name: Atom,
) -> Option<&'props PropertyInfo> {
crate::utils::lookup_property(self.interner, props, shape_id, name)
}
/// Check private brand compatibility for object subtyping.
///
/// Private brands are used for nominal typing of classes with private fields.
/// If both source and target have private brands, they must be the same.
/// If target has a brand but source doesn't (e.g., object literal), this fails.
/// Returns false if brands don't match, true otherwise (including when neither has a brand).
pub(crate) fn check_private_brand_compatibility(
&self,
source: &[PropertyInfo],
target: &[PropertyInfo],
) -> bool {
// Fast path: if neither side has non-public properties, there can't be any
// private brands. This avoids the expensive resolve_atom + starts_with scan
// on every property.
let target_has_nonpublic = target.iter().any(|p| p.visibility != Visibility::Public);
if !target_has_nonpublic {
// No non-public target properties → no brand to check against
return true;
}
let source_brand = source.iter().find(|p| {
p.visibility != Visibility::Public && {
let name = self.interner.resolve_atom(p.name);
name.starts_with("__private_brand_")
}
});
let target_brand = target.iter().find(|p| {
p.visibility != Visibility::Public && {
let name = self.interner.resolve_atom(p.name);
name.starts_with("__private_brand_")
}
});
// Check private brand compatibility
match (source_brand, target_brand) {
(Some(s_brand), Some(t_brand)) => {
// Both have private brands - they must match exactly
let s_brand_name = self.interner.resolve_atom(s_brand.name);
let t_brand_name = self.interner.resolve_atom(t_brand.name);
s_brand_name == t_brand_name
}
(None, Some(_)) => {
// Target has a private brand but source doesn't
// This happens when assigning object literal to class with private members
// Object literals can never have private brands, so this fails
false
}
_ => {
// Neither has a brand, or source has brand but target doesn't - both OK
true
}
}
}
/// Check object subtyping (structural with nominal optimization).
///
/// Validates that source object is a subtype of target object by checking:
/// 1. **Fast path**: Nominal inheritance check (O(1) for class instances)
/// 2. Private brand compatibility (for nominal class typing with private fields)
/// 3. For each target property, source must have a compatible property
pub(crate) fn check_object_subtype(
&mut self,
source: &ObjectShape,
source_shape_id: Option<ObjectShapeId>,
target: &ObjectShape,
) -> SubtypeResult {
// Private brand checking for nominal typing of classes with private fields
if !self.check_private_brand_compatibility(&source.properties, &target.properties) {
return SubtypeResult::False;
}
// Fast fail for private/protected members: check these first so unrelated
// class instances can fail before expensive public method comparison.
for t_prop in &target.properties {
if t_prop.visibility == Visibility::Public {
continue;
}
let Some(s_prop) =
self.lookup_property(&source.properties, source_shape_id, t_prop.name)
else {
return SubtypeResult::False;
};
let result = self.check_property_compatibility(s_prop, t_prop);
if !result.is_true() {
return result;
}
}
let source_len = source.properties.len();
let target_len = target.properties.len();
let use_merge_scan =
source_shape_id.is_none() || source_len <= target_len.saturating_mul(4);
if use_merge_scan {
return self.check_object_subtype_merge_scan(source, target);
}
// For each property in target, source must have a compatible property
for t_prop in &target.properties {
// Private/protected members were handled in the fast-fail prepass.
if t_prop.visibility != Visibility::Public {
continue;
}
let s_prop = self.lookup_property(&source.properties, source_shape_id, t_prop.name);
let result = match s_prop {
Some(sp) => self.check_property_compatibility(sp, t_prop),
None => {
// Private/Protected properties cannot be missing, even if optional
if t_prop.visibility != Visibility::Public {
return SubtypeResult::False;
}
// Property missing - only OK if target property is optional
if t_prop.optional {
SubtypeResult::True
} else {
SubtypeResult::False
}
}
};
if !result.is_true() {
return result;
}
}
SubtypeResult::True
}
fn check_object_subtype_merge_scan(
&mut self,
source: &ObjectShape,
target: &ObjectShape,
) -> SubtypeResult {
let s_props = &source.properties;
let t_props = &target.properties;
let mut s_idx = 0;
for t_prop in t_props {
if t_prop.visibility != Visibility::Public {
continue;
}
while s_idx < s_props.len() && s_props[s_idx].name < t_prop.name {
s_idx += 1;
}
if s_idx < s_props.len() && s_props[s_idx].name == t_prop.name {
let result = self.check_property_compatibility(&s_props[s_idx], t_prop);
if !result.is_true() {
return result;
}
s_idx += 1;
continue;
}
// Property missing - only OK if target property is optional and public
if t_prop.visibility != Visibility::Public {
return SubtypeResult::False;
}
if !t_prop.optional {
return SubtypeResult::False;
}
}
SubtypeResult::True
}
/// Check if a source property is compatible with a target property.
///
/// This validates property compatibility for structural object subtyping:
///
/// ## Rules:
/// 1. **Optional compatibility**: Optional in source can't satisfy required in target
/// - `{ x?: number }` ≤ `{ x: number }` ❌
/// - `{ x: number }` ≤ `{ x?: number }` ✅
///
/// 2. **Readonly compatibility**: TypeScript allows readonly source to satisfy mutable target
/// - `{ readonly x: number }` ≤ `{ x: number }` ✅ (readonly is on the reference)
/// - `{ x: number }` ≤ `{ readonly x: number }` ✅
///
/// 3. **Type compatibility**: Source type must be subtype of target type
/// - Methods use bivariant checking (both directions)
/// - Properties use contravariant checking
///
/// 4. **Write type compatibility**: For mutable properties with different write types,
/// target's write type must be subtype of source's (contravariance for writes)
///
/// Check property compatibility between source and target properties.
///
/// This implements **Rule #26: Split Accessors (Getter/Setter Variance)**.
///
/// ## Split Accessor Variance
///
/// Properties can have different types for reading (getter) vs writing (setter):
/// ```typescript
/// class C {
/// private _x: string | number;
/// get x(): string { return this._x as string; }
/// set x(v: string | number) { this._x = v; }
/// }
/// ```
///
/// In this example, reading `x` yields `string`, but writing accepts `string | number`.
///
/// ## Subtyping Rules
///
/// For `source_prop <: target_prop`:
///
/// 1. **Read types are COVARIANT**: `source.read <: target.read`
/// - When reading from source, we get something that's safe to use as target's read type
///
/// 2. **Write types are CONTRAVARIANT**: `target.write <: source.write`
/// - When writing to target, we accept something that's also safe for source
/// - This ensures source can accept everything target can write
///
/// 3. **Readonly properties**: If target property is readonly, we only check read types
/// - You can't write to a readonly target, so write type doesn't matter
///
/// ## Example
///
/// ```typescript
/// class Base {
/// get x(): string { return "hello"; }
/// set x(v: string | number) {}
/// }
///
/// class Derived extends Base {
/// get x(): string { return "world"; } // OK: string <: string
/// set x(v: string) {} // OK: string <: string | number (contravariant)
/// }
/// ```
///
/// ## Additional Checks
///
/// - Optional properties: source optional can't satisfy target required
/// - Readonly properties: source readonly can't satisfy target mutable
pub(crate) fn check_property_compatibility(
&mut self,
source: &PropertyInfo,
target: &PropertyInfo,
) -> SubtypeResult {
// Rule: Private and Protected properties are nominal.
if target.visibility != Visibility::Public {
if source.parent_id != target.parent_id {
// Trace: Property nominal mismatch
if let Some(tracer) = &mut self.tracer
&& !tracer.on_mismatch_dyn(
crate::diagnostics::SubtypeFailureReason::PropertyNominalMismatch {
property_name: source.name,
},
)
{
return SubtypeResult::False;
}
return SubtypeResult::False;
}
} else if source.visibility != Visibility::Public {
// Cannot assign private/protected source to public target
// Trace: Property visibility mismatch
if let Some(tracer) = &mut self.tracer
&& !tracer.on_mismatch_dyn(
crate::diagnostics::SubtypeFailureReason::PropertyVisibilityMismatch {
property_name: source.name,
source_visibility: source.visibility,
target_visibility: target.visibility,
},
)
{
return SubtypeResult::False;
}
return SubtypeResult::False;
}
// Check optional compatibility
// Optional in source can't satisfy required in target
if source.optional && !target.optional {
// Trace: Optional property cannot satisfy required property
if let Some(tracer) = &mut self.tracer
&& !tracer.on_mismatch_dyn(
crate::diagnostics::SubtypeFailureReason::OptionalPropertyRequired {
property_name: source.name,
},
)
{
return SubtypeResult::False;
}
return SubtypeResult::False;
}
// Note: TypeScript does NOT reject readonly source → mutable target for
// individual properties. `{ readonly x: number }` IS assignable to `{ x: number }`.
// Readonly on properties is a usage constraint, not a structural typing constraint.
// This is different from ReadonlyArray vs Array, where structural differences exist.
// Rule #26: Split Accessors (Getter/Setter Variance)
//
// Properties with split accessors (get/set) have different types for reading vs writing:
// - Read type (getter): covariant - source.read must be subtype of target.read
// - Write type (setter): contravariant - target.write must be subtype of source.write
//
// For readonly properties in target, we only check read type (no writes allowed)
// For mutable properties, we check both read and write types
// 1. Check READ type (covariant): source.read <: target.read
let source_read = self.optional_property_type(source);
let target_read = self.optional_property_type(target);
let allow_bivariant = source.is_method || target.is_method;
// Rule #26: Split Accessors - Covariant reads
// Source read type must be subtype of target read type
if source_read != target_read
&& !self
.check_subtype_with_method_variance(source_read, target_read, allow_bivariant)
.is_true()
{
return SubtypeResult::False;
}
// Rule #26: Split Accessors - Contravariant writes
// For mutable target properties WITH DIFFERENT READ/WRITE TYPES, check write type compatibility
// Target write type must be subtype of source write type (contravariance)
//
// IMPORTANT: This contravariant check only applies to "split accessors" where the
// property has different types for reading vs writing (e.g., getter returns `string`,
// setter accepts `string | number`). For regular properties where read and write types
// are the same, TypeScript uses covariant checking for both.
//
// Without this condition, we would incorrectly reject valid assignments like:
// - { a: string } <: { a?: string } (required to optional)
// - { x: undefined } <: { x?: number } (undefined to optional)
let has_split_accessor =
source.write_type != source.type_id || target.write_type != target.type_id;
if !target.readonly && has_split_accessor {
let source_write = self.optional_property_write_type(source);
let target_write = self.optional_property_write_type(target);
// Contravariant writes: target.write must be subtype of source.write
// This ensures that anything we can write to target is also safe to write to source
if target_write != source_write
&& !self
.check_subtype_with_method_variance(target_write, source_write, allow_bivariant)
.is_true()
{
return SubtypeResult::False;
}
}
SubtypeResult::True
}
/// Check string index signature compatibility between source and target.
///
/// Validates that string index signatures are compatible, handling:
/// - **Both have string index**: Source index must be subtype of target index
/// - **Only target has string index**: All source properties must be compatible with target's index
/// - **Only source has string index**: Compatible (target accepts string access via index)
/// - **Neither has string index**: Compatible (no string index constraint)
///
/// ## Readonly Constraints:
/// - If target index is readonly, source index can be readonly or mutable
/// - If target index is mutable, source index must be mutable (readonly source not compatible)
pub(crate) fn check_string_index_compatibility(
&mut self,
source: &ObjectShape,
target: &ObjectShape,
) -> SubtypeResult {
let Some(ref t_string_idx) = target.string_index else {
return SubtypeResult::True; // Target has no string index constraint
};
match &source.string_index {
Some(s_string_idx) => {
// Source string index must be subtype of target
if s_string_idx.readonly && !t_string_idx.readonly {
return SubtypeResult::False;
}
if !self
.check_subtype(s_string_idx.value_type, t_string_idx.value_type)
.is_true()
{
return SubtypeResult::False;
}
SubtypeResult::True
}
None => {
// Target has string index, source doesn't have a string index.
// Check if source has a number index — in TypeScript, a numeric index
// signature implies a string index (JS converts numeric keys to strings).
// So `{ [n: number]: T }` is assignable to `{ [s: string]: T }` when
// the value types are compatible.
if let Some(s_number_idx) = &source.number_index {
if s_number_idx.readonly && !t_string_idx.readonly {
return SubtypeResult::False;
}
return self.check_subtype(s_number_idx.value_type, t_string_idx.value_type);
}
// All source properties must be compatible with target's string index.
// Implicit Index Signature Rule: Source must have at least one property
// to satisfy the index signature requirement implicitly.
if source.properties.is_empty() {
return SubtypeResult::False;
}
for prop in &source.properties {
if !t_string_idx.readonly && prop.readonly {
return SubtypeResult::False;
}
let prop_type = self.optional_property_type(prop);
if !self
.check_subtype(prop_type, t_string_idx.value_type)
.is_true()
{
return SubtypeResult::False;
}
}
SubtypeResult::True
}
}
}
/// Check number index signature compatibility between source and target objects.
///
/// Validates that number index signatures (`[key: number]: T`) are compatible
/// when checking if source is a subtype of target.
///
/// ## TypeScript Soundness:
/// - **Both have number index**: Source index must be subtype of target index
/// - **Only target has number index**: Source must provide a compatible number/string index
/// - **Only source has number index**: Compatible (target accepts numeric access via index)
/// - **Neither has number index**: Source must have compatible numeric property names
/// (for index-less source objects assigned to indexed targets)
pub(crate) fn check_number_index_compatibility(
&mut self,
source: &ObjectShape,
target: &ObjectShape,
) -> SubtypeResult {
let Some(ref t_number_idx) = target.number_index else {
return SubtypeResult::True; // Target has no number index constraint
};
match &source.number_index {
Some(s_number_idx) => {
// Source number index must be subtype of target
if s_number_idx.readonly && !t_number_idx.readonly {
return SubtypeResult::False;
}
if !self
.check_subtype(s_number_idx.value_type, t_number_idx.value_type)
.is_true()
{
return SubtypeResult::False;
}
SubtypeResult::True
}
None if source.string_index.is_some() => {
// A compatible string index can satisfy numeric index access.
let Some(s_string_idx) = source.string_index.as_ref() else {
return SubtypeResult::False;
};
if s_string_idx.readonly && !t_number_idx.readonly {
return SubtypeResult::False;
}
if !self
.check_subtype(s_string_idx.value_type, t_number_idx.value_type)
.is_true()
{
return SubtypeResult::False;
}
SubtypeResult::True
}
None => {
// Check any numeric-keyed source properties against the target's
// number index type. If a numeric property has an incompatible type,
// the assignment fails.
//
// Implicit Index Signature Rule:
// If the source has no index signature, it is considered to have one
// implicitly IF AND ONLY IF it has properties that match the index key type.
// If there are NO numeric properties, the source does NOT satisfy the
// numeric index signature requirement.
let mut found_numeric_prop = false;
for prop in &source.properties {
if !utils::is_numeric_property_name(self.interner, prop.name) {
continue;
}
found_numeric_prop = true;
if !t_number_idx.readonly && prop.readonly {
return SubtypeResult::False;
}
let prop_type = self.optional_property_type(prop);
if !self
.check_subtype_with_method_variance(
prop_type,
t_number_idx.value_type,
prop.is_method,
)
.is_true()
{
return SubtypeResult::False;
}
}
if found_numeric_prop {
SubtypeResult::True
} else {
SubtypeResult::False
}
}
}
}
/// Check object with index signature subtyping.
///
/// Validates subtype compatibility between two objects that both have index signatures.
/// This requires:
/// 1. Named property compatibility (all target properties must exist in source)
/// 2. String index signature compatibility
/// 3. Number index signature compatibility
/// 4. All source properties must be compatible with target index signatures
/// 5. If source has both string and number indexes, they must be compatible
pub(crate) fn check_object_with_index_subtype(
&mut self,
source: &ObjectShape,
source_shape_id: Option<ObjectShapeId>,
target: &ObjectShape,
) -> SubtypeResult {
// First check named properties (nominal + structural)
// Note: We pass the full shapes to enable nominal inheritance check
if !self
.check_object_subtype(source, source_shape_id, target)
.is_true()
{
return SubtypeResult::False;
}
// Check string index signature compatibility
if !self
.check_string_index_compatibility(source, target)
.is_true()
{
return SubtypeResult::False;
}
// Check number index signature compatibility
if !self
.check_number_index_compatibility(source, target)
.is_true()
{
return SubtypeResult::False;
}
if !self
.check_properties_against_index_signatures(&source.properties, target)
.is_true()
{
return SubtypeResult::False;
}
// If source has string index, all number-indexed properties must be compatible
// (since number converts to string for property access)
if let (Some(s_string_idx), Some(s_number_idx)) =
(&source.string_index, &source.number_index)
&& !self
.check_subtype(s_number_idx.value_type, s_string_idx.value_type)
.is_true()
{
// This is a constraint violation in the source itself
return SubtypeResult::False;
}
SubtypeResult::True
}
/// Check object with index signature to plain object subtyping.
///
/// Validates that a source object with an index signature can be a subtype of
/// a target object with only named properties. For each target property:
/// 1. Look up the property by name in source (including via index signatures)
/// 2. Check property compatibility (optional, readonly, type, `write_type`)
/// 3. If property not found in source, check if index signature can satisfy it
pub(crate) fn check_object_with_index_to_object(
&mut self,
source: &ObjectShape,
source_shape_id: ObjectShapeId,
target: &[PropertyInfo],
) -> SubtypeResult {
for t_prop in target {
if let Some(sp) =
self.lookup_property(&source.properties, Some(source_shape_id), t_prop.name)
{
// Visibility check (Nominal)
if t_prop.visibility != Visibility::Public {
if sp.parent_id != t_prop.parent_id {
return SubtypeResult::False;
}
} else if sp.visibility != Visibility::Public {
// Cannot assign private/protected source to public target
return SubtypeResult::False;
}
// Check optional compatibility
if sp.optional && !t_prop.optional {
return SubtypeResult::False;
}
// NOTE: TypeScript allows readonly source to satisfy mutable target
// (readonly is a constraint on the reference, not structural compatibility)
let source_type = self.optional_property_type(sp);
let target_type = self.optional_property_type(t_prop);
let allow_bivariant = sp.is_method || t_prop.is_method;
if !self
.check_subtype_with_method_variance(source_type, target_type, allow_bivariant)
.is_true()
{
return SubtypeResult::False;
}
if !t_prop.readonly
&& (sp.write_type != sp.type_id || t_prop.write_type != t_prop.type_id)
{
let source_write = self.optional_property_write_type(sp);
let target_write = self.optional_property_write_type(t_prop);
if !self
.check_subtype_with_method_variance(
target_write,
source_write,
allow_bivariant,
)
.is_true()
{
return SubtypeResult::False;
}
}
} else if !self
.check_missing_property_against_index_signatures(source, t_prop)
.is_true()
{
return SubtypeResult::False;
}
}
SubtypeResult::True
}
/// Check if a missing target property can be satisfied by source index signatures.
///
/// When a target property doesn't exist in the source object, the source's index
/// signatures can potentially satisfy it:
/// - If property name is numeric, check against number index signature
/// - Always check against string index signature (since numbers convert to strings)
pub(crate) fn check_missing_property_against_index_signatures(
&mut self,
source: &ObjectShape,
target_prop: &PropertyInfo,
) -> SubtypeResult {
// Required properties cannot be satisfied by index signatures (soundness).
// An index signature { [k: string]: V } admits the empty object {},
// but a required property means the target does NOT admit {}.
// This is a fundamental set-theoretic mismatch, not just a TS compatibility rule.
if !target_prop.optional {
return SubtypeResult::False;
}
// Private/Protected properties cannot be satisfied by index signatures.
// They must be explicitly present in the source and match nominally.
if target_prop.visibility != Visibility::Public {
return SubtypeResult::False;
}
// Check if property name matches index signatures
// Numeric property names can match number index signatures
// All property names can match string index signatures (numbers convert to strings)
let target_type = self.optional_property_type(target_prop);
if utils::is_numeric_property_name(self.interner, target_prop.name)
&& let Some(number_idx) = &source.number_index
{
if number_idx.readonly && !target_prop.readonly {
return SubtypeResult::False;
}
if !self
.check_subtype_with_method_variance(
number_idx.value_type,
target_type,
target_prop.is_method,
)
.is_true()
{
return SubtypeResult::False;
}
return SubtypeResult::True;
}
if let Some(string_idx) = &source.string_index {
if string_idx.readonly && !target_prop.readonly {
return SubtypeResult::False;
}
if !self
.check_subtype_with_method_variance(
string_idx.value_type,
target_type,
target_prop.is_method,
)
.is_true()
{
return SubtypeResult::False;
}
return SubtypeResult::True;
}
// No matching index signature
// For optional properties, this is OK
// For required properties, this is an error
if !target_prop.optional {
SubtypeResult::False
} else {
SubtypeResult::True
}
}
/// Check that source properties are compatible with target index signatures.
///
/// When a target has an index signature, all source properties must satisfy it:
/// - String index: All string-named properties must be compatible with index type
/// - Number index: All numerically-named properties must be compatible with index type
pub(crate) fn check_properties_against_index_signatures(
&mut self,
source: &[PropertyInfo],
target: &ObjectShape,
) -> SubtypeResult {
let string_index = target.string_index.as_ref();
let number_index = target.number_index.as_ref();
if string_index.is_none() && number_index.is_none() {
return SubtypeResult::True;
}
for prop in source {
// If target declares this property explicitly, its compatibility is
// checked via named-property rules. Don't also force it through the
// index signature value type (tsc behavior for intersections like
// `{ a: X } & { [k: string]: Y }` where `a` is validated against `X`).
if target
.properties
.binary_search_by_key(&prop.name, |p| p.name)
.is_ok()
{
continue;
}
let prop_type = self.optional_property_type(prop);
let allow_bivariant = prop.is_method;
if let Some(number_idx) = number_index {
let is_numeric = utils::is_numeric_property_name(self.interner, prop.name);
if is_numeric
&& !self
.check_subtype_with_method_variance(
prop_type,
number_idx.value_type,
allow_bivariant,
)
.is_true()
{
return SubtypeResult::False;
}
if is_numeric && !number_idx.readonly && prop.readonly {
return SubtypeResult::False;
}
}
if let Some(string_idx) = string_index {
if !string_idx.readonly && prop.readonly {
return SubtypeResult::False;
}
if !self
.check_subtype_with_method_variance(
prop_type,
string_idx.value_type,
allow_bivariant,
)
.is_true()
{
return SubtypeResult::False;
}
}
}
SubtypeResult::True
}
/// Check simple object to object with index signature.
///
/// Validates that a source object with only named properties is a subtype of
/// a target object with an index signature. This requires:
/// 1. All target named properties must have compatible source properties
/// 2. All source properties must be compatible with the index signature type
pub(crate) fn check_object_to_indexed(
&mut self,
source: &[PropertyInfo],
source_shape_id: Option<ObjectShapeId>,
target: &ObjectShape,
) -> SubtypeResult {
// First check named properties match
// Create temporary ObjectShape for source to enable nominal check
let source_shape = ObjectShape {
flags: ObjectFlags::empty(),
properties: source.to_vec(),
string_index: None,
number_index: None,
symbol: None, // Source doesn't have a symbol (just properties)
};
if !self
.check_object_subtype(&source_shape, source_shape_id, target)
.is_true()
{
return SubtypeResult::False;
}
// A target number index signature requires the source to provide
// number-compatible indexing via a number or string index signature.
// A plain object with only named properties cannot satisfy arbitrary
// numeric index access.
if !self
.check_number_index_compatibility(&source_shape, target)
.is_true()
{
return SubtypeResult::False;
}
self.check_properties_against_index_signatures(source, target)
}
/// Get the effective type of an optional property for reading.
///
/// Optional properties in TypeScript can be undefined even if their type doesn't
/// explicitly include undefined. This function adds undefined to the type unless
/// exactOptionalPropertyTypes is enabled.
pub(crate) fn optional_property_type(&self, prop: &PropertyInfo) -> TypeId {
if prop.optional && !self.exact_optional_property_types {
self.interner.union2(prop.type_id, TypeId::UNDEFINED)
} else {
prop.type_id
}
}
/// Get the effective write type of an optional property.
pub(crate) fn optional_property_write_type(&self, prop: &PropertyInfo) -> TypeId {
if prop.optional && !self.exact_optional_property_types {
self.interner.union2(prop.write_type, TypeId::UNDEFINED)
} else {
prop.write_type
}
}
}