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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
//! Element access, object literal, super keyword, and await type computation.
use crate::state::{CheckerState, EnumKind};
use tsz_parser::parser::NodeIndex;
use tsz_parser::parser::syntax_kind_ext;
use tsz_scanner::SyntaxKind;
use tsz_solver::{TypeId, Visibility};
const MAX_AWAIT_DEPTH: u32 = 10;
impl<'a> CheckerState<'a> {
/// Get the type of an element access expression (e.g., arr[0], obj["prop"]).
///
/// Handles element access with optional chaining, index signatures,
/// and nullish coalescing.
pub(crate) fn get_type_of_element_access(&mut self, idx: NodeIndex) -> TypeId {
use tsz_solver::operations_property::PropertyAccessResult;
let Some(node) = self.ctx.arena.get(idx) else {
return TypeId::ERROR;
};
let Some(access) = self.ctx.arena.get_access_expr(node) else {
return TypeId::ERROR;
};
// In parse-recovery cases like `number[]`, the bracket argument is
// missing and TS reports parser error TS1011. The expression before
// `[` is still a primitive type keyword used as a value and should
// emit TS2693.
if access.name_or_argument.is_none()
&& let Some(expr_node) = self.ctx.arena.get(access.expression)
{
let keyword_name = if expr_node.kind == SyntaxKind::Identifier as u16 {
self.ctx.arena.get_identifier(expr_node).and_then(|ident| {
match ident.escaped_text.as_str() {
"number" => Some("number"),
"string" => Some("string"),
"boolean" => Some("boolean"),
"symbol" => Some("symbol"),
"void" => Some("void"),
"undefined" => Some("undefined"),
"null" => Some("null"),
"any" => Some("any"),
"unknown" => Some("unknown"),
"never" => Some("never"),
"object" => Some("object"),
"bigint" => Some("bigint"),
_ => None,
}
})
} else {
match expr_node.kind {
k if k == SyntaxKind::NumberKeyword as u16 => Some("number"),
k if k == SyntaxKind::StringKeyword as u16 => Some("string"),
k if k == SyntaxKind::BooleanKeyword as u16 => Some("boolean"),
k if k == SyntaxKind::SymbolKeyword as u16 => Some("symbol"),
k if k == SyntaxKind::VoidKeyword as u16 => Some("void"),
k if k == SyntaxKind::UndefinedKeyword as u16 => Some("undefined"),
k if k == SyntaxKind::NullKeyword as u16 => Some("null"),
k if k == SyntaxKind::AnyKeyword as u16 => Some("any"),
k if k == SyntaxKind::UnknownKeyword as u16 => Some("unknown"),
k if k == SyntaxKind::NeverKeyword as u16 => Some("never"),
k if k == SyntaxKind::ObjectKeyword as u16 => Some("object"),
k if k == SyntaxKind::BigIntKeyword as u16 => Some("bigint"),
_ => None,
}
};
if let Some(keyword_name) = keyword_name {
self.error_type_only_value_at(keyword_name, access.expression);
return TypeId::ERROR;
}
}
// Get the type of the object
let object_type = self.get_type_of_node(access.expression);
let object_type = self.evaluate_application_type(object_type);
// Handle optional chain continuations: for `o?.b["c"]`, when processing `["c"]`,
// the object type from `o?.b` includes `undefined`. Strip nullish types when this
// element access is a continuation of an optional chain.
let object_type = if !access.question_dot_token
&& crate::optional_chain::is_optional_chain(self.ctx.arena, access.expression)
{
let (non_nullish, _) = self.split_nullish_type(object_type);
non_nullish.unwrap_or(object_type)
} else {
object_type
};
let literal_string = self.get_literal_string_from_node(access.name_or_argument);
let numeric_string_index = literal_string
.as_deref()
.and_then(|name| self.get_numeric_index_from_string(name));
let literal_index = self
.get_literal_index_from_node(access.name_or_argument)
.or(numeric_string_index);
if let Some(name) = literal_string.as_deref()
&& self.is_global_this_expression(access.expression)
{
let property_type =
self.resolve_global_this_property_type(name, access.name_or_argument);
if property_type == TypeId::ERROR {
return TypeId::ERROR;
}
return self.apply_flow_narrowing(idx, property_type);
}
// Don't report errors for any/error types - check BEFORE accessibility
// to prevent cascading errors when the object type is already invalid
if object_type == TypeId::ANY {
return TypeId::ANY;
}
if object_type == TypeId::ERROR {
return TypeId::ERROR;
}
// TS18013: Check for private identifier access outside of class
// Private identifiers (#foo) can only be accessed from within the class that declares them
if let Some(name_node) = self.ctx.arena.get(access.name_or_argument)
&& name_node.kind == tsz_scanner::SyntaxKind::PrivateIdentifier as u16
{
// Get the property name
let prop_name = if let Some(ident) = self.ctx.arena.get_identifier(name_node) {
&ident.escaped_text
} else {
"#"
};
// Check if we're inside the class that declares this private identifier
let (symbols, _saw_class_scope) =
self.resolve_private_identifier_symbols(access.name_or_argument);
// If we didn't find the symbol, it's being accessed outside the class that declares it
if symbols.is_empty() {
use crate::diagnostics::{diagnostic_codes, diagnostic_messages, format_message};
// Try to get the class name from the type
let class_name = self
.get_class_name_from_type(object_type)
.unwrap_or_else(|| "the class".to_string());
let message = format_message(
diagnostic_messages::PROPERTY_IS_NOT_ACCESSIBLE_OUTSIDE_CLASS_BECAUSE_IT_HAS_A_PRIVATE_IDENTIFIER,
&[prop_name, &class_name],
);
self.error_at_node(
access.name_or_argument,
&message,
diagnostic_codes::PROPERTY_IS_NOT_ACCESSIBLE_OUTSIDE_CLASS_BECAUSE_IT_HAS_A_PRIVATE_IDENTIFIER,
);
return TypeId::ERROR;
}
}
if let Some(name) = literal_string.as_deref() {
if !self.check_property_accessibility(
access.expression,
name,
access.name_or_argument,
object_type,
) {
return TypeId::ERROR;
}
} else if let Some(index) = literal_index {
let name = index.to_string();
if !self.check_property_accessibility(
access.expression,
&name,
access.name_or_argument,
object_type,
) {
return TypeId::ERROR;
}
}
let object_type = self.resolve_type_for_property_access(object_type);
if object_type == TypeId::ANY {
return TypeId::ANY;
}
if object_type == TypeId::ERROR {
return TypeId::ERROR;
}
// Element access on `never` returns `never` (bottom type propagation).
if object_type == TypeId::NEVER {
return TypeId::NEVER;
}
let (object_type_for_access, nullish_cause) = self.split_nullish_type(object_type);
let Some(object_type_for_access) = object_type_for_access else {
if access.question_dot_token {
return TypeId::UNDEFINED;
}
if let Some(cause) = nullish_cause {
// Type is entirely nullish - emit TS18050 "The value X cannot be used here"
self.report_nullish_object(access.expression, cause, true);
}
return TypeId::ERROR;
};
// Type is possibly nullish (e.g., Foo | undefined) - emit TS18048/TS2532
// unless optional chaining is used
if let Some(cause) = nullish_cause
&& !access.question_dot_token
{
self.report_nullish_object(access.expression, cause, false);
}
let index_type = self.get_type_of_node(access.name_or_argument);
// Propagate error from index expression to suppress cascading errors
if index_type == TypeId::ERROR {
return TypeId::ERROR;
}
// TS2538: Type cannot be used as an index type
if self.type_is_invalid_index_type(index_type) {
use crate::diagnostics::{diagnostic_codes, diagnostic_messages, format_message};
let index_type_str = self.format_type(index_type);
let message = format_message(
diagnostic_messages::TYPE_CANNOT_BE_USED_AS_AN_INDEX_TYPE,
&[&index_type_str],
);
self.error_at_node(
access.name_or_argument,
&message,
diagnostic_codes::TYPE_CANNOT_BE_USED_AS_AN_INDEX_TYPE,
);
return TypeId::ERROR;
}
let literal_string_is_none = literal_string.is_none();
let mut result_type = None;
let mut report_no_index = false;
let mut use_index_signature_check = true;
if let Some(name) = literal_string.as_deref() {
if self.is_type_only_import_equals_namespace_expr(access.expression) {
if let Some(ns_name) = self.entity_name_text(access.expression) {
self.error_namespace_used_as_value_at(&ns_name, access.expression);
if let Some(sym_id) = self.resolve_identifier_symbol(access.expression)
&& self.alias_resolves_to_type_only(sym_id)
{
self.error_type_only_value_at(&ns_name, access.expression);
}
}
return TypeId::ERROR;
}
if let Some(member_type) =
self.resolve_namespace_value_member(object_type_for_access, name)
{
result_type = Some(member_type);
use_index_signature_check = false;
} else if self.namespace_has_type_only_member(object_type_for_access, name) {
if self.is_unresolved_import_symbol(access.expression) {
return TypeId::ERROR;
}
// Don't emit TS2693 in heritage clause context — the heritage
// checker will emit the appropriate error (e.g., TS2689).
if self
.find_enclosing_heritage_clause(access.name_or_argument)
.is_none()
{
// Emit TS2708 for namespace member access (e.g., ns.Interface())
// This is "Cannot use namespace as a value"
if let Some(ns_name) = self.entity_name_text(access.expression) {
self.error_namespace_used_as_value_at(&ns_name, access.expression);
}
// Also emit TS2693 for the type-only member itself
self.error_type_only_value_at(name, access.name_or_argument);
}
return TypeId::ERROR;
}
}
if result_type.is_none()
&& literal_index.is_none()
&& let Some((string_keys, number_keys)) =
self.get_literal_key_union_from_type(index_type)
{
let total_keys = string_keys.len() + number_keys.len();
if total_keys > 1 || literal_string_is_none {
if !string_keys.is_empty() && number_keys.is_empty() {
use_index_signature_check = false;
}
let mut types = Vec::new();
if !string_keys.is_empty() {
match self.get_element_access_type_for_literal_keys(
object_type_for_access,
&string_keys,
) {
Some(result) => types.push(result),
None => report_no_index = true,
}
}
if !number_keys.is_empty() {
match self.get_element_access_type_for_literal_number_keys(
object_type_for_access,
&number_keys,
) {
Some(result) => types.push(result),
None => report_no_index = true,
}
}
if report_no_index {
result_type = Some(TypeId::ANY);
} else if !types.is_empty() {
result_type = Some(tsz_solver::utils::union_or_single(self.ctx.types, types));
}
}
}
if result_type.is_none()
&& let Some(property_name) = self.get_literal_string_from_node(access.name_or_argument)
&& numeric_string_index.is_none()
{
// Resolve type references (Ref, TypeQuery, etc.) before property access lookup
let resolved_type = self.resolve_type_for_property_access(object_type_for_access);
let result = self.resolve_property_access_with_env(resolved_type, &property_name);
result_type = match result {
PropertyAccessResult::Success {
type_id,
write_type,
..
} => {
use_index_signature_check = false;
// In write context (assignment target), prefer the setter type.
let effective = if self.ctx.skip_flow_narrowing {
write_type.unwrap_or(type_id)
} else {
type_id
};
Some(effective)
}
PropertyAccessResult::PossiblyNullOrUndefined { property_type, .. } => {
use_index_signature_check = false;
// Use ERROR instead of UNKNOWN to prevent TS2571 errors
Some(property_type.unwrap_or(TypeId::ERROR))
}
PropertyAccessResult::IsUnknown => {
use_index_signature_check = false;
// TS2339: Property does not exist on type 'unknown'
// Use the same error as TypeScript for property access on unknown
self.error_property_not_exist_at(
&property_name,
object_type_for_access,
access.name_or_argument,
);
Some(TypeId::ERROR)
}
PropertyAccessResult::PropertyNotFound { .. } => {
// TS2576 parity for element access on instance/super with a static member name.
if self.is_super_expression(access.expression)
&& let Some(ref class_info) = self.ctx.enclosing_class
&& let Some(base_idx) = self.get_base_class_idx(class_info.class_idx)
&& self.is_method_member_in_class_hierarchy(base_idx, &property_name, true)
== Some(true)
{
use crate::diagnostics::{
diagnostic_codes, diagnostic_messages, format_message,
};
let base_name = self.get_class_name_from_decl(base_idx);
let static_member_name = format!("{base_name}.{property_name}");
let object_type_str = self.format_type(object_type);
let message = format_message(
diagnostic_messages::PROPERTY_DOES_NOT_EXIST_ON_TYPE_DID_YOU_MEAN_TO_ACCESS_THE_STATIC_MEMBER_INSTEAD,
&[&property_name, &object_type_str, &static_member_name],
);
self.error_at_node(
access.name_or_argument,
&message,
diagnostic_codes::PROPERTY_DOES_NOT_EXIST_ON_TYPE_DID_YOU_MEAN_TO_ACCESS_THE_STATIC_MEMBER_INSTEAD,
);
use_index_signature_check = false;
Some(TypeId::ERROR)
} else if self.is_super_expression(access.expression)
&& let Some(ref class_info) = self.ctx.enclosing_class
&& let Some(base_idx) = self.get_base_class_idx(class_info.class_idx)
&& self.is_method_member_in_class_hierarchy(base_idx, &property_name, true)
== Some(false)
{
self.error_property_not_exist_at(
&property_name,
object_type_for_access,
access.name_or_argument,
);
use_index_signature_check = false;
Some(TypeId::ERROR)
} else if !self.is_super_expression(access.expression)
&& let Some((class_idx, is_static_access)) =
self.resolve_class_for_access(access.expression, object_type_for_access)
&& !is_static_access
&& self.is_method_member_in_class_hierarchy(class_idx, &property_name, true)
== Some(true)
{
use crate::diagnostics::{
diagnostic_codes, diagnostic_messages, format_message,
};
let class_name = self.get_class_name_from_decl(class_idx);
let static_member_name = format!("{class_name}.{property_name}");
let object_type_str = self.format_type(object_type);
let message = format_message(
diagnostic_messages::PROPERTY_DOES_NOT_EXIST_ON_TYPE_DID_YOU_MEAN_TO_ACCESS_THE_STATIC_MEMBER_INSTEAD,
&[&property_name, &object_type_str, &static_member_name],
);
self.error_at_node(
access.name_or_argument,
&message,
diagnostic_codes::PROPERTY_DOES_NOT_EXIST_ON_TYPE_DID_YOU_MEAN_TO_ACCESS_THE_STATIC_MEMBER_INSTEAD,
);
use_index_signature_check = false;
Some(TypeId::ERROR)
} else if !self.is_super_expression(access.expression)
&& let Some((class_idx, is_static_access)) =
self.resolve_class_for_access(access.expression, object_type_for_access)
&& !is_static_access
&& self.is_method_member_in_class_hierarchy(class_idx, &property_name, true)
== Some(false)
{
self.error_property_not_exist_at(
&property_name,
object_type_for_access,
access.name_or_argument,
);
use_index_signature_check = false;
Some(TypeId::ERROR)
} else {
// TS2339 parity for element access on `typeof const enum` with missing member.
// Const enums do not have a reverse mapping, so they shouldn't fall back to
// TS7053 string index signature checks like regular enums do.
let mut is_const_enum = false;
if let Some(sym_id) = self.enum_symbol_from_type(object_type_for_access)
&& let Some(symbol) = self.ctx.binder.get_symbol(sym_id)
&& symbol.flags & tsz_binder::symbol_flags::CONST_ENUM != 0
{
is_const_enum = true;
}
if is_const_enum {
self.error_property_not_exist_at(
&property_name,
object_type_for_access,
access.name_or_argument,
);
use_index_signature_check = false;
Some(TypeId::ERROR)
} else {
// CRITICAL FIX: Don't immediately return ANY when property is not found.
// Let it fall through to check for index signatures below.
// This allows map["foo"] to work when map has [key: string]: boolean
None
}
}
}
};
}
if result_type.is_none()
&& let Some(index) = literal_index
&& !self.is_array_like_type(object_type_for_access)
{
let property_name = index.to_string();
let resolved_type = self.resolve_type_for_property_access(object_type_for_access);
let result = self.resolve_property_access_with_env(resolved_type, &property_name);
result_type = match result {
PropertyAccessResult::Success {
type_id,
write_type,
..
} => {
use_index_signature_check = false;
// In write context (assignment target), prefer the setter type.
let effective = if self.ctx.skip_flow_narrowing {
write_type.unwrap_or(type_id)
} else {
type_id
};
Some(effective)
}
PropertyAccessResult::PossiblyNullOrUndefined { property_type, .. } => {
use_index_signature_check = false;
Some(property_type.unwrap_or(TypeId::ERROR))
}
PropertyAccessResult::IsUnknown => {
use_index_signature_check = false;
self.error_property_not_exist_at(
&property_name,
object_type_for_access,
access.name_or_argument,
);
Some(TypeId::ERROR)
}
PropertyAccessResult::PropertyNotFound { .. } => None,
};
}
// Handle non-integer numeric literals (e.g., c[1.1], c[-1]) as property name access.
// Integer literals are handled above via literal_index. Non-integer numeric literals
// aren't covered by get_literal_string_from_node or get_literal_index_from_node,
// so we need to try property access using their text representation.
if result_type.is_none()
&& literal_index.is_none()
&& literal_string_is_none
&& let Some(node) = self.ctx.arena.get(access.name_or_argument)
&& node.kind == SyntaxKind::NumericLiteral as u16
&& let Some(lit) = self.ctx.arena.get_literal(node)
{
let property_name = &lit.text;
let resolved_type = self.resolve_type_for_property_access(object_type_for_access);
let result = self.resolve_property_access_with_env(resolved_type, property_name);
if let PropertyAccessResult::Success {
type_id,
write_type,
..
} = result
{
use_index_signature_check = false;
let effective = if self.ctx.skip_flow_narrowing {
write_type.unwrap_or(type_id)
} else {
type_id
};
result_type = Some(effective);
}
}
let mut result_type = result_type.unwrap_or_else(|| {
self.get_element_access_type(object_type_for_access, index_type, literal_index)
});
if result_type == TypeId::ERROR
&& let Some(index) = literal_index
&& let Some(tuple_elements) =
crate::query_boundaries::type_computation_access::tuple_elements(
self.ctx.types,
object_type_for_access,
)
{
let has_rest_tail = tuple_elements.last().is_some_and(|element| element.rest);
if !has_rest_tail && index >= tuple_elements.len() {
self.error_at_node(
access.name_or_argument,
&format!(
"Tuple type of length '{}' has no element at index '{}'.",
tuple_elements.len(),
index
),
crate::diagnostics::diagnostic_codes::TUPLE_TYPE_OF_LENGTH_HAS_NO_ELEMENT_AT_INDEX,
);
}
}
if use_index_signature_check
&& self.should_report_no_index_signature(
object_type_for_access,
index_type,
literal_index,
)
{
report_no_index = true;
}
if report_no_index {
// Suppress TS7053 for expando bracket assignments on function types.
// When `func["prop"] = value` and the object is callable, tsc does not emit
// TS7053 — it treats this as a valid JS-style property expansion.
// We detect write context via `skip_flow_narrowing` which is set by
// `get_type_of_assignment_target`.
let is_expando_function_write = self.ctx.skip_flow_narrowing
&& tsz_solver::visitor::is_function_type(self.ctx.types, object_type_for_access);
if !is_expando_function_write {
self.error_no_index_signature_at(index_type, object_type, access.name_or_argument);
}
}
if let Some(cause) = nullish_cause {
if access.question_dot_token {
result_type = self
.ctx
.types
.factory()
.union(vec![result_type, TypeId::UNDEFINED]);
} else if !report_no_index {
self.report_possibly_nullish_object(access.expression, cause);
}
}
self.apply_flow_narrowing(idx, result_type)
}
/// Get the element access type for array/tuple/object with index signatures.
///
/// Computes the type when accessing an element using an index.
/// Uses `ElementAccessEvaluator` from solver for structured error handling.
pub(crate) fn get_element_access_type(
&mut self,
object_type: TypeId,
index_type: TypeId,
literal_index: Option<usize>,
) -> TypeId {
// Normalize index type for enum values
let solver_index_type = if let Some(index) = literal_index {
self.ctx.types.literal_number(index as f64)
} else if self
.enum_symbol_from_type(index_type)
.is_some_and(|sym_id| self.enum_kind(sym_id) == Some(EnumKind::Numeric))
{
// Numeric enum values are number-like at runtime.
TypeId::NUMBER
} else {
index_type
};
self.ctx
.types
.resolve_element_access_type(object_type, solver_index_type, literal_index)
}
/// Get the type of the `super` keyword.
///
/// Computes the type of `super` expressions:
/// - `super()` calls: returns the base class constructor type
/// - `super.property` access: returns the base class instance type
/// - Static context: returns constructor type
/// - Instance context: returns instance type
pub(crate) fn get_type_of_super_keyword(&mut self, idx: NodeIndex) -> TypeId {
// Check super expression validity and emit any errors
self.check_super_expression(idx);
let Some(class_info) = self.ctx.enclosing_class.clone() else {
return TypeId::ERROR;
};
let mut extends_expr_idx = NodeIndex::NONE;
let mut extends_type_args = None;
if let Some(current_class) = self.ctx.arena.get_class_at(class_info.class_idx)
&& let Some(heritage_clauses) = ¤t_class.heritage_clauses
{
for &clause_idx in &heritage_clauses.nodes {
let Some(heritage) = self.ctx.arena.get_heritage_clause_at(clause_idx) else {
continue;
};
if heritage.token != SyntaxKind::ExtendsKeyword as u16 {
continue;
}
let Some(&type_idx) = heritage.types.nodes.first() else {
continue;
};
if let Some(expr_type_args) = self.ctx.arena.get_expr_type_args_at(type_idx) {
extends_expr_idx = expr_type_args.expression;
extends_type_args = expr_type_args.type_arguments.clone();
} else {
extends_expr_idx = type_idx;
}
break;
}
}
// Detect `super(...)` usage by checking if the parent is a CallExpression whose callee is `super`.
let is_super_call = self
.ctx
.arena
.get_extended(idx)
.and_then(|ext| self.ctx.arena.get(ext.parent).map(|n| (ext.parent, n)))
.and_then(|(parent_idx, parent_node)| {
if parent_node.kind != syntax_kind_ext::CALL_EXPRESSION {
return None;
}
let call = self.ctx.arena.get_call_expr(parent_node)?;
Some(call.expression == idx && parent_idx.is_some())
})
.unwrap_or(false);
// Static context: the current `this` type is the current class constructor type.
let is_static_context = self.current_this_type().is_some_and(|this_ty| {
if let Some(sym_id) = self.ctx.binder.get_node_symbol(class_info.class_idx) {
this_ty == self.get_type_of_symbol(sym_id)
} else if let Some(class_node) = self.ctx.arena.get(class_info.class_idx) {
if let Some(class) = self.ctx.arena.get_class(class_node) {
this_ty == self.get_class_constructor_type(class_info.class_idx, class)
} else {
false
}
} else {
false
}
});
if is_super_call || is_static_context {
if extends_expr_idx.is_some()
&& let Some(ctor_type) = self.base_constructor_type_from_expression(
extends_expr_idx,
extends_type_args.as_ref(),
)
{
return ctor_type;
}
let Some(base_class_idx) = self.get_base_class_idx(class_info.class_idx) else {
return TypeId::ERROR;
};
let Some(base_node) = self.ctx.arena.get(base_class_idx) else {
return TypeId::ERROR;
};
let Some(base_class) = self.ctx.arena.get_class(base_node) else {
return TypeId::ERROR;
};
return self.get_class_constructor_type(base_class_idx, base_class);
}
if extends_expr_idx.is_some()
&& let Some(instance_type) = self
.base_instance_type_from_expression(extends_expr_idx, extends_type_args.as_ref())
{
return instance_type;
}
let Some(base_class_idx) = self.get_base_class_idx(class_info.class_idx) else {
return TypeId::ERROR;
};
let Some(base_node) = self.ctx.arena.get(base_class_idx) else {
return TypeId::ERROR;
};
let Some(base_class) = self.ctx.arena.get_class(base_node) else {
return TypeId::ERROR;
};
self.get_class_instance_type(base_class_idx, base_class)
}
/// Get the type of a node with a fallback.
///
/// Returns the computed type, or the fallback if the computed type is ERROR.
pub fn get_type_of_node_or(&mut self, idx: NodeIndex, fallback: TypeId) -> TypeId {
let ty = self.get_type_of_node(idx);
if ty == TypeId::ERROR { fallback } else { ty }
}
/// Get the type of an object literal expression.
///
/// Computes the type of object literals like `{ x: 1, y: 2 }` or `{ foo, bar }`.
/// Handles:
/// - Property assignments: `{ x: value }`
/// - Shorthand properties: `{ x }`
/// - Method shorthands: `{ foo() {} }`
/// - Getters/setters: `{ get foo() {}, set foo(v) {} }`
/// - Spread properties: `{ ...obj }`
/// - Duplicate property detection
/// - Contextual type inference
/// - Implicit any reporting (TS7008)
pub(crate) fn get_type_of_object_literal(&mut self, idx: NodeIndex) -> TypeId {
use crate::diagnostics::{diagnostic_codes, diagnostic_messages, format_message};
use rustc_hash::FxHashMap;
use tsz_common::interner::Atom;
use tsz_solver::PropertyInfo;
let Some(node) = self.ctx.arena.get(idx) else {
return TypeId::ERROR; // Missing node - propagate error
};
let Some(obj) = self.ctx.arena.get_literal_expr(node) else {
return TypeId::ERROR; // Missing object literal data - propagate error
};
// Collect properties from the object literal (later entries override earlier ones)
let mut properties: FxHashMap<Atom, PropertyInfo> = FxHashMap::default();
let mut has_spread = false;
// Track getter/setter names to allow getter+setter pairs with the same name
let mut getter_names: rustc_hash::FxHashSet<Atom> = rustc_hash::FxHashSet::default();
let mut setter_names: rustc_hash::FxHashSet<Atom> = rustc_hash::FxHashSet::default();
let mut explicit_property_names: rustc_hash::FxHashSet<Atom> =
rustc_hash::FxHashSet::default();
// Track which named properties came from explicit assignments (not spreads)
// so we can emit TS2783 when a later spread overwrites them.
// Maps property name atom -> (node_idx for error, property display name)
let mut named_property_nodes: FxHashMap<Atom, (NodeIndex, String)> = FxHashMap::default();
// Skip duplicate property checks for destructuring assignment targets.
// `({ x, y: y1, "y": y1 } = obj)` is valid - same property extracted twice.
let skip_duplicate_check = self.ctx.in_destructuring_target;
// Check for ThisType<T> marker in contextual type (Vue 2 / Options API pattern)
// We need to extract this BEFORE the for loop so it's available for the pop at the end
let marker_this_type: Option<TypeId> = if let Some(ctx_type) = self.ctx.contextual_type {
use tsz_solver::ContextualTypeContext;
let ctx_helper = ContextualTypeContext::with_expected_and_options(
self.ctx.types,
ctx_type,
self.ctx.compiler_options.no_implicit_any,
);
ctx_helper.get_this_type_from_marker()
} else {
None
};
// Push this type onto stack if found (methods will pick it up)
if let Some(this_type) = marker_this_type {
self.ctx.this_type_stack.push(this_type);
}
// Pre-scan: collect getter property names so setter TS7006 checks can
// detect paired getters regardless of declaration order.
let obj_getter_names: rustc_hash::FxHashSet<String> = obj
.elements
.nodes
.iter()
.filter_map(|&elem_idx| {
let elem_node = self.ctx.arena.get(elem_idx)?;
if elem_node.kind != syntax_kind_ext::GET_ACCESSOR {
return None;
}
let accessor = self.ctx.arena.get_accessor(elem_node)?;
self.get_property_name(accessor.name).or_else(|| {
let prop_name_node = self.ctx.arena.get(accessor.name)?;
if prop_name_node.kind
== tsz_parser::parser::syntax_kind_ext::COMPUTED_PROPERTY_NAME
{
let computed = self.ctx.arena.get_computed_property(prop_name_node)?;
let prop_name_type = self.get_type_of_node(computed.expression);
crate::query_boundaries::type_computation_access::literal_property_name(
self.ctx.types,
prop_name_type,
)
.map(|atom| self.ctx.types.resolve_atom(atom))
} else {
None
}
})
})
.collect();
for &elem_idx in &obj.elements.nodes {
let Some(elem_node) = self.ctx.arena.get(elem_idx) else {
continue;
};
// Property assignment: { x: value }
if let Some(prop) = self.ctx.arena.get_property_assignment(elem_node) {
if let Some(prop_name_node) = self.ctx.arena.get(prop.name)
&& prop_name_node.kind
== tsz_parser::parser::syntax_kind_ext::COMPUTED_PROPERTY_NAME
{
// Always run TS2464 validation for computed property names, even when
// the name can be resolved to a literal atom.
self.check_computed_property_name(prop.name);
}
let name_opt = self.get_property_name(prop.name).or_else(|| {
let prop_name_node = self.ctx.arena.get(prop.name)?;
if prop_name_node.kind
== tsz_parser::parser::syntax_kind_ext::COMPUTED_PROPERTY_NAME
{
let computed = self.ctx.arena.get_computed_property(prop_name_node)?;
let prop_name_type = self.get_type_of_node(computed.expression);
crate::query_boundaries::type_computation_access::literal_property_name(
self.ctx.types,
prop_name_type,
)
.map(|atom| self.ctx.types.resolve_atom(atom))
} else {
None
}
});
if let Some(name) = name_opt.clone() {
// Get contextual type for this property.
// For mapped/conditional/application types that contain Lazy references
// (e.g. { [K in keyof Props]: Props[K] } after generic inference),
// evaluate them with the full resolver first so the solver can
// extract property types from the resulting concrete object type.
let property_context_type = if let Some(ctx_type) = self.ctx.contextual_type {
let ctx_type = self.evaluate_contextual_type(ctx_type);
self.ctx.types.contextual_property_type(ctx_type, &name)
} else {
None
};
// Set contextual type for property value
let prev_context = self.ctx.contextual_type;
self.ctx.contextual_type = property_context_type;
// When the parser can't parse a value expression (e.g. `{ a: return; }`),
// it uses the property NAME node as the fallback initializer for error
// recovery (prop.initializer == prop.name). Skip type-checking in that
// case to prevent a spurious TS2304 for the property name identifier.
let value_type = if prop.initializer == prop.name {
TypeId::ANY
} else {
self.get_type_of_node(prop.initializer)
};
// Restore context
self.ctx.contextual_type = prev_context;
// Apply bidirectional type inference - use contextual type to narrow the value type
let value_type = tsz_solver::apply_contextual_type(
self.ctx.types,
value_type,
property_context_type,
);
// Widen literal types for object literal properties (tsc behavior).
// Object literal properties are mutable by default, so `{ x: "a" }`
// produces `{ x: string }`. Only preserve literals when:
// - A const assertion is active (`as const`)
// - A contextual type narrows the property to a literal
let value_type =
if !self.ctx.in_const_assertion && property_context_type.is_none() {
self.widen_literal_type(value_type)
} else {
value_type
};
// Note: TS7008 is NOT emitted for object literal properties.
// tsc only emits TS7008 for class properties, property signatures,
// auto-accessors, and binary expressions.
let name_atom = self.ctx.types.intern_string(&name);
// Check for duplicate property (skip in destructuring targets)
// TS1117: duplicate properties are an error in object literals.
if !skip_duplicate_check
&& explicit_property_names.contains(&name_atom)
&& !self.ctx.has_parse_errors
{
let message = format_message(
diagnostic_messages::AN_OBJECT_LITERAL_CANNOT_HAVE_MULTIPLE_PROPERTIES_WITH_THE_SAME_NAME,
&[&name],
);
self.error_at_node(
prop.name,
&message,
diagnostic_codes::AN_OBJECT_LITERAL_CANNOT_HAVE_MULTIPLE_PROPERTIES_WITH_THE_SAME_NAME,
);
}
explicit_property_names.insert(name_atom);
// Track this named property for TS2783 spread-overwrite checking
named_property_nodes.insert(name_atom, (prop.name, name.clone()));
properties.insert(
name_atom,
PropertyInfo {
name: name_atom,
type_id: value_type,
write_type: value_type,
optional: false,
readonly: false,
is_method: false,
visibility: Visibility::Public,
parent_id: None,
},
);
} else {
// Computed property name that can't be statically resolved (e.g., { [expr]: value })
// Still type-check the computed expression and the value to catch errors like TS2304.
// For contextual typing, use the index signature type from the contextual type.
// E.g., `var o: { [s: string]: (x: string) => number } = { ["" + 0](y) { ... } }`
// should contextually type `y` as `string` from the string index signature.
self.check_computed_property_name(prop.name);
if let Some(prop_name_node) = self.ctx.arena.get(prop.name)
&& prop_name_node.kind
== tsz_parser::parser::syntax_kind_ext::COMPUTED_PROPERTY_NAME
&& let Some(computed) = self.ctx.arena.get_computed_property(prop_name_node)
{
let prop_name_type = self.get_type_of_node(computed.expression);
if let Some(atom) =
crate::query_boundaries::type_computation_access::literal_property_name(
self.ctx.types,
prop_name_type,
)
{
if !skip_duplicate_check
&& explicit_property_names.contains(&atom)
&& !self.ctx.has_parse_errors
{
let name = self.ctx.types.resolve_atom(atom).to_string();
use crate::diagnostics::{diagnostic_codes, diagnostic_messages};
let message = crate::diagnostics::format_message(
diagnostic_messages::AN_OBJECT_LITERAL_CANNOT_HAVE_MULTIPLE_PROPERTIES_WITH_THE_SAME_NAME,
&[&name],
);
self.error_at_node(
prop.name,
&message,
diagnostic_codes::AN_OBJECT_LITERAL_CANNOT_HAVE_MULTIPLE_PROPERTIES_WITH_THE_SAME_NAME,
);
}
explicit_property_names.insert(atom);
}
}
let index_ctx_type = if let Some(ctx_type) = self.ctx.contextual_type {
let ctx_type = self.evaluate_contextual_type(ctx_type);
// Use a synthetic name that won't match any named property,
// causing contextual_property_type to fall back to the index signature.
self.ctx
.types
.contextual_property_type(ctx_type, "__@computed")
} else {
None
};
let prev_context = self.ctx.contextual_type;
self.ctx.contextual_type = index_ctx_type;
self.get_type_of_node(prop.initializer);
self.ctx.contextual_type = prev_context;
}
}
// Shorthand property: { x } - identifier is both name and value
else if elem_node.kind == syntax_kind_ext::SHORTHAND_PROPERTY_ASSIGNMENT {
if let Some(shorthand) = self.ctx.arena.get_shorthand_property(elem_node)
&& let Some(name_node) = self.ctx.arena.get(shorthand.name)
&& let Some(ident) = self.ctx.arena.get_identifier(name_node)
{
let name = ident.escaped_text.clone();
let shorthand_name_idx = shorthand.name;
// Get contextual type for this property
let property_context_type = if let Some(ctx_type) = self.ctx.contextual_type {
let ctx_type = self.evaluate_contextual_type(ctx_type);
self.ctx.types.contextual_property_type(ctx_type, &name)
} else {
None
};
// Set contextual type for shorthand property value
let prev_context = self.ctx.contextual_type;
self.ctx.contextual_type = property_context_type;
let value_type = if self.resolve_identifier_symbol(shorthand_name_idx).is_none()
{
// Don't emit TS18004 for strict reserved words that require `:` syntax.
// Example: `{ class }` — parser already emits TS1005 "':' expected".
// Checker should not also emit TS18004 (cascading error).
//
// Only suppress for ECMAScript reserved words that ALWAYS require `:`
// in object literals. Be conservative — when in doubt, emit TS18004.
let is_strict_reserved = matches!(
name.as_str(),
"break"
| "case"
| "catch"
| "class"
| "const"
| "continue"
| "debugger"
| "default"
| "delete"
| "do"
| "else"
| "enum"
| "export"
| "extends"
| "finally"
| "for"
| "function"
| "if"
| "import"
| "in"
| "instanceof"
| "new"
| "return"
| "super"
| "switch"
| "throw"
| "try"
| "var"
| "void"
| "while"
| "with"
);
// Also suppress TS18004 for obviously invalid names that
// are parser-recovery artifacts (single punctuation characters
// like `:`, `,`, `;` that became shorthand properties during
// error recovery).
let is_obviously_invalid_name = name.len() == 1
&& name
.chars()
.next()
.is_some_and(|c| !c.is_alphanumeric() && c != '_' && c != '$');
if !is_strict_reserved && !is_obviously_invalid_name {
// TS18004: Missing value binding for shorthand property name
// Example: `({ arguments })` inside arrow function where `arguments`
// is not in scope as a value.
let message = format_message(
diagnostic_messages::NO_VALUE_EXISTS_IN_SCOPE_FOR_THE_SHORTHAND_PROPERTY_EITHER_DECLARE_ONE_OR_PROVID,
&[&name],
);
self.error_at_node(
elem_idx,
&message,
diagnostic_codes::NO_VALUE_EXISTS_IN_SCOPE_FOR_THE_SHORTHAND_PROPERTY_EITHER_DECLARE_ONE_OR_PROVID,
);
}
// In destructuring assignment targets, unresolved shorthand names
// are already invalid (TS18004). Don't synthesize a required
// object property from this invalid entry; doing so can produce
// follow-on missing-property errors (e.g. TS2741) that tsc omits.
if self.ctx.in_destructuring_target {
continue;
}
TypeId::ANY
} else {
// Use shorthand_name_idx (the identifier) so that get_type_of_identifier
// is invoked, which calls check_flow_usage and can emit TS2454
// if the variable is used before assignment.
// Using elem_idx (SHORTHAND_PROPERTY_ASSIGNMENT) would return TypeId::ERROR
// since that node kind has no dispatch handler, silently suppressing TS2454.
self.get_type_of_node(shorthand_name_idx)
};
// Restore context
self.ctx.contextual_type = prev_context;
// Apply bidirectional type inference - use contextual type to narrow the value type
let value_type = tsz_solver::apply_contextual_type(
self.ctx.types,
value_type,
property_context_type,
);
// Widen literal types for shorthand properties (same as named properties)
let value_type =
if !self.ctx.in_const_assertion && property_context_type.is_none() {
self.widen_literal_type(value_type)
} else {
value_type
};
// Note: TS7008 is NOT emitted for object literal properties.
// tsc only emits TS7008 for class properties, property signatures,
// auto-accessors, and binary expressions.
let name_atom = self.ctx.types.intern_string(&name);
// Check for duplicate property (skip in destructuring targets)
// TS1117: duplicate properties are an error in object literals.
if !skip_duplicate_check
&& explicit_property_names.contains(&name_atom)
&& !self.ctx.has_parse_errors
{
let message = format_message(
diagnostic_messages::AN_OBJECT_LITERAL_CANNOT_HAVE_MULTIPLE_PROPERTIES_WITH_THE_SAME_NAME,
&[&name],
);
self.error_at_node(
elem_idx,
&message,
diagnostic_codes::AN_OBJECT_LITERAL_CANNOT_HAVE_MULTIPLE_PROPERTIES_WITH_THE_SAME_NAME,
);
}
explicit_property_names.insert(name_atom);
// Track this shorthand property for TS2783 spread-overwrite checking
named_property_nodes.insert(name_atom, (elem_idx, name.clone()));
properties.insert(
name_atom,
PropertyInfo {
name: name_atom,
type_id: value_type,
write_type: value_type,
optional: false,
readonly: false,
is_method: false,
visibility: Visibility::Public,
parent_id: None,
},
);
} else if let Some(shorthand) = self.ctx.arena.get_shorthand_property(elem_node) {
self.check_computed_property_name(shorthand.name);
}
}
// Method shorthand: { foo() {} }
else if let Some(method) = self.ctx.arena.get_method_decl(elem_node) {
let name_opt = self.get_property_name(method.name).or_else(|| {
let prop_name_node = self.ctx.arena.get(method.name)?;
if prop_name_node.kind
== tsz_parser::parser::syntax_kind_ext::COMPUTED_PROPERTY_NAME
{
let computed = self.ctx.arena.get_computed_property(prop_name_node)?;
let prop_name_type = self.get_type_of_node(computed.expression);
crate::query_boundaries::type_computation_access::literal_property_name(
self.ctx.types,
prop_name_type,
)
.map(|atom| self.ctx.types.resolve_atom(atom))
} else {
None
}
});
if let Some(name) = name_opt.clone() {
// Set contextual type for method
let prev_context = self.ctx.contextual_type;
if let Some(ctx_type) = prev_context {
let ctx_type = self.evaluate_contextual_type(ctx_type);
self.ctx.contextual_type =
self.ctx.types.contextual_property_type(ctx_type, &name);
}
// If no explicit ThisType marker exists, use the object literal's
// contextual type as `this` inside method bodies.
let mut pushed_contextual_this = false;
if marker_this_type.is_none()
&& self.current_this_type().is_none()
&& let Some(ctx_type) = prev_context
{
let ctx_type = self.evaluate_contextual_type(ctx_type);
self.ctx.this_type_stack.push(ctx_type);
pushed_contextual_this = true;
}
let method_type = self.get_type_of_function(elem_idx);
if pushed_contextual_this {
self.ctx.this_type_stack.pop();
}
// Restore context
self.ctx.contextual_type = prev_context;
let name_atom = self.ctx.types.intern_string(&name);
// Check for duplicate property (skip in destructuring targets)
// TS1117: duplicate properties are an error in object literals.
if !skip_duplicate_check
&& explicit_property_names.contains(&name_atom)
&& !self.ctx.has_parse_errors
{
let message = format_message(
diagnostic_messages::AN_OBJECT_LITERAL_CANNOT_HAVE_MULTIPLE_PROPERTIES_WITH_THE_SAME_NAME,
&[&name],
);
self.error_at_node(
method.name,
&message,
diagnostic_codes::AN_OBJECT_LITERAL_CANNOT_HAVE_MULTIPLE_PROPERTIES_WITH_THE_SAME_NAME,
);
}
explicit_property_names.insert(name_atom);
properties.insert(
name_atom,
PropertyInfo {
name: name_atom,
type_id: method_type,
write_type: method_type,
optional: false,
readonly: false,
is_method: true, // Object literal methods should be bivariant
visibility: Visibility::Public,
parent_id: None,
},
);
} else {
// Computed method name - still type-check the expression and function body.
// For contextual typing, use the index signature type from the contextual type.
// E.g., `var o: { [s: string]: (x: string) => number } = { ["" + 0](y) { ... } }`
// should contextually type `y` as `string` from the string index signature.
self.check_computed_property_name(method.name);
if let Some(prop_name_node) = self.ctx.arena.get(method.name)
&& prop_name_node.kind
== tsz_parser::parser::syntax_kind_ext::COMPUTED_PROPERTY_NAME
&& let Some(computed) = self.ctx.arena.get_computed_property(prop_name_node)
{
let prop_name_type = self.get_type_of_node(computed.expression);
if let Some(atom) =
crate::query_boundaries::type_computation_access::literal_property_name(
self.ctx.types,
prop_name_type,
)
{
if !skip_duplicate_check
&& explicit_property_names.contains(&atom)
&& !self.ctx.has_parse_errors
{
let name = self.ctx.types.resolve_atom(atom).to_string();
use crate::diagnostics::{diagnostic_codes, diagnostic_messages};
let message = crate::diagnostics::format_message(
diagnostic_messages::AN_OBJECT_LITERAL_CANNOT_HAVE_MULTIPLE_PROPERTIES_WITH_THE_SAME_NAME,
&[&name],
);
self.error_at_node(
method.name,
&message,
diagnostic_codes::AN_OBJECT_LITERAL_CANNOT_HAVE_MULTIPLE_PROPERTIES_WITH_THE_SAME_NAME,
);
}
explicit_property_names.insert(atom);
}
}
let prev_context = self.ctx.contextual_type;
if let Some(ctx_type) = prev_context {
let ctx_type = self.evaluate_contextual_type(ctx_type);
self.ctx.contextual_type = self
.ctx
.types
.contextual_property_type(ctx_type, "__@computed");
}
self.get_type_of_function(elem_idx);
self.ctx.contextual_type = prev_context;
}
}
// Accessor: { get foo() {} } or { set foo(v) {} }
else if let Some(accessor) = self.ctx.arena.get_accessor(elem_node) {
// Check for missing body - error 1005 at end of accessor
if accessor.body.is_none() {
use crate::diagnostics::diagnostic_codes;
// Report at accessor.end - 1 (pointing to the closing paren)
let end_pos = elem_node.end.saturating_sub(1);
self.error_at_position(end_pos, 1, "'{' expected.", diagnostic_codes::EXPECTED);
}
// For setters, check implicit any on parameters (error 7006) and on
// the property name itself (error 7032).
// When a paired getter exists, the setter parameter type is inferred
// from the getter return type (contextually typed, suppress TS7006/7032).
if elem_node.kind == syntax_kind_ext::SET_ACCESSOR {
let name_opt = self.get_property_name(accessor.name).or_else(|| {
let prop_name_type = self.get_type_of_node(accessor.name);
crate::query_boundaries::type_computation_access::literal_property_name(
self.ctx.types,
prop_name_type,
)
.map(|atom| self.ctx.types.resolve_atom(atom))
});
let has_paired_getter = name_opt
.as_ref()
.is_some_and(|name| obj_getter_names.contains(name));
// Check if accessor JSDoc has @param type annotations
let accessor_jsdoc = self.get_jsdoc_for_function(elem_idx);
let mut first_param_lacks_annotation = false;
for ¶m_idx in &accessor.parameters.nodes {
if let Some(param_node) = self.ctx.arena.get(param_idx)
&& let Some(param) = self.ctx.arena.get_parameter(param_node)
{
let has_jsdoc = has_paired_getter
|| self.param_has_inline_jsdoc_type(param_idx)
|| if let Some(ref jsdoc) = accessor_jsdoc {
let pname = self.parameter_name_for_error(param.name);
Self::jsdoc_has_param_type(jsdoc, &pname)
} else {
false
};
if param.type_annotation.is_none() && !has_jsdoc {
first_param_lacks_annotation = true;
}
self.maybe_report_implicit_any_parameter(param, has_jsdoc);
}
}
// TS7032: emit on property name when the setter has no parameter type
// annotation and no paired getter (TSC checks this at accessor symbol
// resolution time; we emit it here during object literal checking).
if first_param_lacks_annotation
&& !has_paired_getter
&& self.ctx.no_implicit_any()
&& let Some(prop_name) = name_opt.as_deref()
{
use crate::diagnostics::diagnostic_codes;
self.error_at_node_msg(
accessor.name,
diagnostic_codes::PROPERTY_IMPLICITLY_HAS_TYPE_ANY_BECAUSE_ITS_SET_ACCESSOR_LACKS_A_PARAMETER_TYPE,
&[prop_name],
);
}
}
let name_opt = self.get_property_name(accessor.name).or_else(|| {
let prop_name_node = self.ctx.arena.get(accessor.name)?;
if prop_name_node.kind
== tsz_parser::parser::syntax_kind_ext::COMPUTED_PROPERTY_NAME
{
let computed = self.ctx.arena.get_computed_property(prop_name_node)?;
let prop_name_type = self.get_type_of_node(computed.expression);
crate::query_boundaries::type_computation_access::literal_property_name(
self.ctx.types,
prop_name_type,
)
.map(|atom| self.ctx.types.resolve_atom(atom))
} else {
None
}
});
if let Some(name) = name_opt.clone() {
// For non-contextual object literals, TypeScript treats `this` inside
// accessors as the object literal under construction. Provide a
// lightweight synthetic receiver so property access checks (TS2339)
// run during accessor body checking.
let mut pushed_synthetic_this = false;
if marker_this_type.is_none() {
let mut this_props: Vec<PropertyInfo> =
properties.values().cloned().collect();
let name_atom = self.ctx.types.intern_string(&name);
if !this_props.iter().any(|p| p.name == name_atom) {
this_props.push(PropertyInfo {
name: name_atom,
type_id: TypeId::ANY,
write_type: TypeId::ANY,
optional: false,
readonly: false,
is_method: false,
visibility: Visibility::Public,
parent_id: None,
});
}
self.ctx
.this_type_stack
.push(self.ctx.types.factory().object(this_props));
pushed_synthetic_this = true;
}
// For getter, infer return type; for setter, use the parameter type
let accessor_type = if elem_node.kind == syntax_kind_ext::GET_ACCESSOR {
// Check getter body/parameters via function checking, but object
// property read type is the getter's return type (not a function type).
self.get_type_of_function(elem_idx);
if accessor.type_annotation.is_none() {
self.infer_getter_return_type(accessor.body)
} else {
self.get_type_from_type_node(accessor.type_annotation)
}
} else {
// Setter: type-check the function body to track variable usage
// (especially for noUnusedParameters/noUnusedLocals checking),
// but use the parameter type annotation for the property type
self.get_type_of_function(elem_idx);
// Extract setter write type from first parameter.
// When no type annotation, fall back to the paired getter's
// return type (mirroring tsc's inference behavior).
accessor
.parameters
.nodes
.first()
.and_then(|¶m_idx| {
let param = self.ctx.arena.get_parameter_at(param_idx)?;
if param.type_annotation.is_none() {
None
} else {
Some(self.get_type_from_type_node(param.type_annotation))
}
})
.or_else(|| {
// No annotation — infer from paired getter's type
let setter_name = name_opt.clone()?;
let name_atom = self.ctx.types.intern_string(&setter_name);
properties.get(&name_atom).map(|p| p.type_id)
})
.unwrap_or(TypeId::ANY)
};
if pushed_synthetic_this {
self.ctx.this_type_stack.pop();
}
if elem_node.kind == syntax_kind_ext::GET_ACCESSOR {
if accessor.type_annotation.is_none() {
use crate::diagnostics::diagnostic_codes;
let self_refs =
self.collect_property_name_references(accessor.body, &name);
if !self_refs.is_empty() {
self.error_at_node_msg(
accessor.name,
diagnostic_codes::IMPLICITLY_HAS_RETURN_TYPE_ANY_BECAUSE_IT_DOES_NOT_HAVE_A_RETURN_TYPE_ANNOTATION,
&[&name],
);
}
}
self.maybe_report_implicit_any_return(
Some(name.clone()),
Some(accessor.name),
accessor_type,
accessor.type_annotation.is_some(),
false,
elem_idx,
);
}
// TS2378: A 'get' accessor must return a value.
// Check if the getter has a body but no return statement with a value.
if elem_node.kind == syntax_kind_ext::GET_ACCESSOR && accessor.body.is_some() {
let has_return = self.body_has_return_with_value(accessor.body);
let falls_through = self.function_body_falls_through(accessor.body);
if !has_return && falls_through {
use crate::diagnostics::diagnostic_codes;
self.error_at_node(
accessor.name,
"A 'get' accessor must return a value.",
diagnostic_codes::A_GET_ACCESSOR_MUST_RETURN_A_VALUE,
);
}
}
let name_atom = self.ctx.types.intern_string(&name);
// Check for duplicate property - but allow getter+setter pairs
// A getter and setter with the same name is valid, not a duplicate
let is_getter = elem_node.kind == syntax_kind_ext::GET_ACCESSOR;
let is_complementary_pair = if is_getter {
setter_names.contains(&name_atom) && !getter_names.contains(&name_atom)
} else {
getter_names.contains(&name_atom) && !setter_names.contains(&name_atom)
};
// TS1117: duplicate properties are an error in object literals.
if !skip_duplicate_check
&& explicit_property_names.contains(&name_atom)
&& !is_complementary_pair
&& !self.ctx.has_parse_errors
{
let message = format_message(
diagnostic_messages::AN_OBJECT_LITERAL_CANNOT_HAVE_MULTIPLE_PROPERTIES_WITH_THE_SAME_NAME,
&[&name],
);
self.error_at_node(
accessor.name,
&message,
diagnostic_codes::AN_OBJECT_LITERAL_CANNOT_HAVE_MULTIPLE_PROPERTIES_WITH_THE_SAME_NAME,
);
}
explicit_property_names.insert(name_atom);
if is_getter {
getter_names.insert(name_atom);
} else {
setter_names.insert(name_atom);
}
// Merge getter/setter into a single property with separate
// read (type_id) and write (write_type) types.
if let Some(existing) = properties.get(&name_atom) {
let (read_type, write_type) = if is_getter {
// Getter arriving after setter
(accessor_type, existing.write_type)
} else {
// Setter arriving after getter
(existing.type_id, accessor_type)
};
properties.insert(
name_atom,
PropertyInfo {
name: name_atom,
type_id: read_type,
write_type,
optional: false,
readonly: false,
is_method: false,
visibility: Visibility::Public,
parent_id: None,
},
);
} else {
properties.insert(
name_atom,
PropertyInfo {
name: name_atom,
type_id: accessor_type,
write_type: accessor_type,
optional: false,
readonly: false,
is_method: false,
visibility: Visibility::Public,
parent_id: None,
},
);
}
} else {
// Computed accessor name - still type-check the expression and body
self.check_computed_property_name(accessor.name);
if let Some(prop_name_node) = self.ctx.arena.get(accessor.name)
&& prop_name_node.kind
== tsz_parser::parser::syntax_kind_ext::COMPUTED_PROPERTY_NAME
&& let Some(computed) = self.ctx.arena.get_computed_property(prop_name_node)
{
let prop_name_type = self.get_type_of_node(computed.expression);
if let Some(atom) =
crate::query_boundaries::type_computation_access::literal_property_name(
self.ctx.types,
prop_name_type,
)
{
let is_getter =
elem_node.kind == tsz_parser::parser::syntax_kind_ext::GET_ACCESSOR;
let is_complementary_pair = if is_getter {
setter_names.contains(&atom) && !getter_names.contains(&atom)
} else {
getter_names.contains(&atom) && !setter_names.contains(&atom)
};
if !skip_duplicate_check
&& explicit_property_names.contains(&atom)
&& !is_complementary_pair
&& !self.ctx.has_parse_errors
{
let name = self.ctx.types.resolve_atom(atom).to_string();
use crate::diagnostics::{diagnostic_codes, diagnostic_messages};
let message = crate::diagnostics::format_message(
diagnostic_messages::AN_OBJECT_LITERAL_CANNOT_HAVE_MULTIPLE_PROPERTIES_WITH_THE_SAME_NAME,
&[&name],
);
self.error_at_node(
accessor.name,
&message,
diagnostic_codes::AN_OBJECT_LITERAL_CANNOT_HAVE_MULTIPLE_PROPERTIES_WITH_THE_SAME_NAME,
);
}
explicit_property_names.insert(atom);
}
}
if elem_node.kind == syntax_kind_ext::GET_ACCESSOR {
self.get_type_of_function(elem_idx);
// TS2378: A 'get' accessor must return a value.
if accessor.body.is_some() {
let has_return = self.body_has_return_with_value(accessor.body);
let falls_through = self.function_body_falls_through(accessor.body);
if !has_return && falls_through {
use crate::diagnostics::diagnostic_codes;
self.error_at_node(
accessor.name,
"A 'get' accessor must return a value.",
diagnostic_codes::A_GET_ACCESSOR_MUST_RETURN_A_VALUE,
);
}
}
}
}
}
// Spread assignment: { ...obj }
else if elem_node.kind == syntax_kind_ext::SPREAD_ELEMENT
|| elem_node.kind == syntax_kind_ext::SPREAD_ASSIGNMENT
{
has_spread = true;
let spread_expr = self
.ctx
.arena
.get_spread(elem_node)
.map(|spread| spread.expression)
.or_else(|| {
self.ctx
.arena
.get_unary_expr_ex(elem_node)
.map(|unary| unary.expression)
});
if let Some(spread_expr) = spread_expr {
let spread_type = self.get_type_of_node(spread_expr);
// TS2698: Spread types may only be created from object types
let resolved_spread = self.resolve_type_for_property_access(spread_type);
let resolved_spread = self.resolve_lazy_type(resolved_spread);
if !crate::query_boundaries::type_computation_access::is_valid_spread_type(
self.ctx.types,
resolved_spread,
) {
self.report_spread_not_object_type(elem_idx);
}
let spread_props = self.collect_object_spread_properties(spread_type);
// TS2783: Check if any earlier named properties will be
// overwritten by required properties from this spread.
// Only when strict null checks are enabled.
if self.ctx.strict_null_checks() {
for sp in &spread_props {
if !sp.optional
&& let Some((prop_node, prop_name)) =
named_property_nodes.get(&sp.name)
{
let message = format_message(
diagnostic_messages::IS_SPECIFIED_MORE_THAN_ONCE_SO_THIS_USAGE_WILL_BE_OVERWRITTEN,
&[prop_name],
);
self.error_at_node(
*prop_node,
&message,
diagnostic_codes::IS_SPECIFIED_MORE_THAN_ONCE_SO_THIS_USAGE_WILL_BE_OVERWRITTEN,
);
}
}
}
// After TS2783 check, clear the named-property tracking
// for properties that the spread overwrites (so only the
// first occurrence can trigger the diagnostic, not later
// spreads which are spread-vs-spread and exempt).
for prop in &spread_props {
named_property_nodes.remove(&prop.name);
}
for prop in spread_props {
properties.insert(prop.name, prop);
}
}
}
// Other element types (e.g., unknown AST node kinds) are silently skipped
}
let properties: Vec<PropertyInfo> = properties.into_values().collect();
// Object literals with spreads are not fresh (no excess property checking)
let object_type = if has_spread {
self.ctx.types.factory().object(properties)
} else {
self.ctx.types.factory().object_fresh(properties)
};
// NOTE: Freshness is now tracked on the TypeId via ObjectFlags.
// This fixes the "Zombie Freshness" bug by distinguishing fresh vs
// non-fresh object types at interning time.
// Pop this type from stack if we pushed it earlier
if marker_this_type.is_some() {
self.ctx.this_type_stack.pop();
}
object_type
}
/// Collect properties from a spread expression in an object literal.
///
/// Given the type of the spread expression, extracts all properties that would
/// be spread into the object literal.
pub(crate) fn collect_object_spread_properties(
&mut self,
type_id: TypeId,
) -> Vec<tsz_solver::PropertyInfo> {
let resolved = self.resolve_type_for_property_access(type_id);
let resolved = self.resolve_lazy_type(resolved);
self.ctx.types.collect_object_spread_properties(resolved)
}
// =========================================================================
// Await Expression Type Computation
// =========================================================================
/// Get the type of an await expression with contextual typing support.
///
/// Propagate contextual type to await operand.
///
/// When awaiting with a contextual type T (e.g., `const x: T = await expr`),
/// the operand should receive T | `PromiseLike`<T> as its contextual type.
/// This allows both immediate values and Promises to be inferred correctly.
///
/// Example:
/// ```typescript
/// async function fn(): Promise<Obj> {
/// const obj: Obj = await { key: "value" }; // Operand gets Obj | PromiseLike<Obj>
/// return obj;
/// }
/// ```
pub(crate) fn get_type_of_await_expression(&mut self, idx: NodeIndex) -> TypeId {
let Some(node) = self.ctx.arena.get(idx) else {
return TypeId::ERROR;
};
let Some(unary) = self.ctx.arena.get_unary_expr_ex(node) else {
return TypeId::ERROR;
};
// Match tsc's special-case for `await(...)` inside sync functions.
// In these contexts TypeScript treats this as an unresolved identifier use
// and reports TS2311 instead of await-context diagnostics.
if !self.ctx.in_async_context()
&& self.ctx.function_depth > 0
&& !self.ctx.binder.is_external_module()
&& self.await_expression_uses_call_like_syntax(idx)
{
if let Some((start, _)) = self.get_node_span(idx) {
let message = crate::diagnostics::format_message(
crate::diagnostics::diagnostic_messages::CANNOT_FIND_NAME_DID_YOU_MEAN_TO_WRITE_THIS_IN_AN_ASYNC_FUNCTION,
&["await"],
);
self.error_at_position(
start,
5,
&message,
crate::diagnostics::diagnostic_codes::CANNOT_FIND_NAME_DID_YOU_MEAN_TO_WRITE_THIS_IN_AN_ASYNC_FUNCTION,
);
}
return TypeId::ANY;
}
// Propagate contextual type to await operand
// If we have a contextual type T, transform it to T | PromiseLike<T>
let prev_context = self.ctx.contextual_type;
if let Some(contextual) = prev_context {
// Skip transformation for error types, any, unknown, or never
if contextual != TypeId::ANY
&& contextual != TypeId::UNKNOWN
&& contextual != TypeId::NEVER
&& !self.type_contains_error(contextual)
{
// Create PromiseLike<T> type
let promise_like_t = self.get_promise_like_type(contextual);
// Create union: T | PromiseLike<T>
let union_context = self
.ctx
.types
.factory()
.union(vec![contextual, promise_like_t]);
// Set the union as the contextual type for the operand
self.ctx.contextual_type = Some(union_context);
}
}
// Get the type of the await operand with transformed contextual type
let expr_type = self.get_type_of_node(unary.expression);
// Restore the original contextual type
self.ctx.contextual_type = prev_context;
// Recursively unwrap Promise<T> to get T (simulating Awaited<T>)
// TypeScript's await recursively unwraps nested Promises.
// For example: await Promise<Promise<number>> should have type `number`
let mut current_type = expr_type;
let mut depth = 0;
while let Some(inner) = self.promise_like_return_type_argument(current_type) {
current_type = inner;
depth += 1;
if depth > MAX_AWAIT_DEPTH {
break;
}
}
current_type
}
fn await_expression_uses_call_like_syntax(&self, idx: NodeIndex) -> bool {
let Some((start, end)) = self.get_node_span(idx) else {
return false;
};
if end <= start {
return false;
}
let Some(source_file) = self.ctx.arena.source_files.first() else {
return false;
};
source_file
.text
.get(start as usize..end as usize)
.is_some_and(|text| text.starts_with("await("))
}
/// Get `PromiseLike`<T> for a given type T.
///
/// Helper function for await contextual typing.
/// Returns the type application `PromiseLike`<T>.
///
/// If `PromiseLike` is not available in lib files, returns the base type T.
/// This is a conservative fallback that still allows correct typing.
fn get_promise_like_type(&mut self, type_arg: TypeId) -> TypeId {
// Try to resolve PromiseLike from lib files
if let Some(promise_like_base) = self.resolve_global_interface_type("PromiseLike") {
// Check if we successfully got a PromiseLike type
if promise_like_base != TypeId::ANY
&& promise_like_base != TypeId::ERROR
&& promise_like_base != TypeId::UNKNOWN
{
// Create PromiseLike<T> application
return self
.ctx
.types
.application(promise_like_base, vec![type_arg]);
}
}
// Fallback: If PromiseLike is not available, return the base type
// This allows await to work even without full lib files
type_arg
}
}