tsc-ts 0.0.4 → 0.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (584) hide show
  1. package/README.md +33 -1
  2. package/dist/api/compiler/ast-utilities.d.ts +82 -0
  3. package/dist/api/compiler/ast-utilities.js +462 -0
  4. package/dist/api/compiler/ast.d.ts +2350 -0
  5. package/dist/api/compiler/ast.js +11206 -0
  6. package/dist/api/compiler/astnav.d.ts +37 -0
  7. package/dist/api/compiler/astnav.js +767 -0
  8. package/dist/api/compiler/binder-utilities.d.ts +182 -0
  9. package/dist/api/compiler/binder-utilities.js +1240 -0
  10. package/dist/api/compiler/binder.d.ts +33 -0
  11. package/dist/api/compiler/binder.js +2358 -0
  12. package/dist/api/compiler/character-codes.d.ts +161 -0
  13. package/dist/api/compiler/character-codes.js +160 -0
  14. package/dist/api/compiler/checker-calls.d.ts +46 -0
  15. package/dist/api/compiler/checker-calls.js +1640 -0
  16. package/dist/api/compiler/checker-classes.d.ts +30 -0
  17. package/dist/api/compiler/checker-classes.js +582 -0
  18. package/dist/api/compiler/checker-contextual.d.ts +77 -0
  19. package/dist/api/compiler/checker-contextual.js +1136 -0
  20. package/dist/api/compiler/checker-declaration-order.d.ts +12 -0
  21. package/dist/api/compiler/checker-declaration-order.js +356 -0
  22. package/dist/api/compiler/checker-declarations.d.ts +33 -0
  23. package/dist/api/compiler/checker-declarations.js +888 -0
  24. package/dist/api/compiler/checker-declared-types.d.ts +48 -0
  25. package/dist/api/compiler/checker-declared-types.js +787 -0
  26. package/dist/api/compiler/checker-decorators.d.ts +26 -0
  27. package/dist/api/compiler/checker-decorators.js +562 -0
  28. package/dist/api/compiler/checker-deprecation.d.ts +33 -0
  29. package/dist/api/compiler/checker-deprecation.js +315 -0
  30. package/dist/api/compiler/checker-destructuring.d.ts +34 -0
  31. package/dist/api/compiler/checker-destructuring.js +584 -0
  32. package/dist/api/compiler/checker-elaboration.d.ts +15 -0
  33. package/dist/api/compiler/checker-elaboration.js +290 -0
  34. package/dist/api/compiler/checker-emit-helpers.d.ts +58 -0
  35. package/dist/api/compiler/checker-emit-helpers.js +154 -0
  36. package/dist/api/compiler/checker-emit-resolver.d.ts +75 -0
  37. package/dist/api/compiler/checker-emit-resolver.js +579 -0
  38. package/dist/api/compiler/checker-evaluator.d.ts +27 -0
  39. package/dist/api/compiler/checker-evaluator.js +188 -0
  40. package/dist/api/compiler/checker-expressions.d.ts +67 -0
  41. package/dist/api/compiler/checker-expressions.js +1351 -0
  42. package/dist/api/compiler/checker-features.d.ts +6 -0
  43. package/dist/api/compiler/checker-features.js +354 -0
  44. package/dist/api/compiler/checker-flow.d.ts +86 -0
  45. package/dist/api/compiler/checker-flow.js +169 -0
  46. package/dist/api/compiler/checker-functions.d.ts +43 -0
  47. package/dist/api/compiler/checker-functions.js +1002 -0
  48. package/dist/api/compiler/checker-generated-code.d.ts +25 -0
  49. package/dist/api/compiler/checker-generated-code.js +168 -0
  50. package/dist/api/compiler/checker-globals.d.ts +14 -0
  51. package/dist/api/compiler/checker-globals.js +37 -0
  52. package/dist/api/compiler/checker-grammar.d.ts +35 -0
  53. package/dist/api/compiler/checker-grammar.js +2573 -0
  54. package/dist/api/compiler/checker-heritage.d.ts +28 -0
  55. package/dist/api/compiler/checker-heritage.js +900 -0
  56. package/dist/api/compiler/checker-inference.d.ts +179 -0
  57. package/dist/api/compiler/checker-inference.js +2105 -0
  58. package/dist/api/compiler/checker-iteration.d.ts +115 -0
  59. package/dist/api/compiler/checker-iteration.js +857 -0
  60. package/dist/api/compiler/checker-javascript.d.ts +42 -0
  61. package/dist/api/compiler/checker-javascript.js +441 -0
  62. package/dist/api/compiler/checker-jsdoc.d.ts +30 -0
  63. package/dist/api/compiler/checker-jsdoc.js +320 -0
  64. package/dist/api/compiler/checker-jsx.d.ts +94 -0
  65. package/dist/api/compiler/checker-jsx.js +1433 -0
  66. package/dist/api/compiler/checker-literals.d.ts +6 -0
  67. package/dist/api/compiler/checker-literals.js +43 -0
  68. package/dist/api/compiler/checker-members.d.ts +198 -0
  69. package/dist/api/compiler/checker-members.js +2126 -0
  70. package/dist/api/compiler/checker-modules.d.ts +85 -0
  71. package/dist/api/compiler/checker-modules.js +2141 -0
  72. package/dist/api/compiler/checker-narrowing.d.ts +120 -0
  73. package/dist/api/compiler/checker-narrowing.js +2797 -0
  74. package/dist/api/compiler/checker-object-literals.d.ts +14 -0
  75. package/dist/api/compiler/checker-object-literals.js +479 -0
  76. package/dist/api/compiler/checker-operators.d.ts +33 -0
  77. package/dist/api/compiler/checker-operators.js +1040 -0
  78. package/dist/api/compiler/checker-overloads.d.ts +7 -0
  79. package/dist/api/compiler/checker-overloads.js +270 -0
  80. package/dist/api/compiler/checker-property-access.d.ts +34 -0
  81. package/dist/api/compiler/checker-property-access.js +672 -0
  82. package/dist/api/compiler/checker-services.d.ts +49 -0
  83. package/dist/api/compiler/checker-services.js +995 -0
  84. package/dist/api/compiler/checker-signatures.d.ts +55 -0
  85. package/dist/api/compiler/checker-signatures.js +788 -0
  86. package/dist/api/compiler/checker-source-file.d.ts +27 -0
  87. package/dist/api/compiler/checker-source-file.js +619 -0
  88. package/dist/api/compiler/checker-statements.d.ts +18 -0
  89. package/dist/api/compiler/checker-statements.js +226 -0
  90. package/dist/api/compiler/checker-super.d.ts +13 -0
  91. package/dist/api/compiler/checker-super.js +241 -0
  92. package/dist/api/compiler/checker-symbol-types.d.ts +67 -0
  93. package/dist/api/compiler/checker-symbol-types.js +1885 -0
  94. package/dist/api/compiler/checker-symbols.d.ts +181 -0
  95. package/dist/api/compiler/checker-symbols.js +1782 -0
  96. package/dist/api/compiler/checker-type-factory.d.ts +142 -0
  97. package/dist/api/compiler/checker-type-factory.js +2501 -0
  98. package/dist/api/compiler/checker-type-nodes.d.ts +26 -0
  99. package/dist/api/compiler/checker-type-nodes.js +828 -0
  100. package/dist/api/compiler/checker-type-operators.d.ts +109 -0
  101. package/dist/api/compiler/checker-type-operators.js +1842 -0
  102. package/dist/api/compiler/checker-types.d.ts +1027 -0
  103. package/dist/api/compiler/checker-types.js +1697 -0
  104. package/dist/api/compiler/checker-unused.d.ts +19 -0
  105. package/dist/api/compiler/checker-unused.js +524 -0
  106. package/dist/api/compiler/checker-utilities.d.ts +33 -0
  107. package/dist/api/compiler/checker-utilities.js +141 -0
  108. package/dist/api/compiler/checker.d.ts +491 -0
  109. package/dist/api/compiler/checker.js +912 -0
  110. package/dist/api/compiler/command-line.d.ts +32 -0
  111. package/dist/api/compiler/command-line.js +383 -0
  112. package/dist/api/compiler/compile-program.d.ts +118 -0
  113. package/dist/api/compiler/compile-program.js +384 -0
  114. package/dist/api/compiler/diagnostic-locales.d.ts +22 -0
  115. package/dist/api/compiler/diagnostic-locales.js +64 -0
  116. package/dist/api/compiler/diagnostic-messages.d.ts +2166 -0
  117. package/dist/api/compiler/diagnostic-messages.js +184 -0
  118. package/dist/api/compiler/diagnostics.d.ts +167 -0
  119. package/dist/api/compiler/diagnostics.js +820 -0
  120. package/dist/api/compiler/emitter.d.ts +71 -0
  121. package/dist/api/compiler/emitter.js +327 -0
  122. package/dist/api/compiler/file-include.d.ts +117 -0
  123. package/dist/api/compiler/file-include.js +536 -0
  124. package/dist/api/compiler/file-loader.d.ts +261 -0
  125. package/dist/api/compiler/file-loader.js +1257 -0
  126. package/dist/api/compiler/file-system.d.ts +51 -0
  127. package/dist/api/compiler/file-system.js +132 -0
  128. package/dist/api/compiler/flow.d.ts +60 -0
  129. package/dist/api/compiler/flow.js +45 -0
  130. package/dist/api/compiler/instantiation.d.ts +74 -0
  131. package/dist/api/compiler/instantiation.js +799 -0
  132. package/dist/api/compiler/jsdoc.d.ts +75 -0
  133. package/dist/api/compiler/jsdoc.js +1229 -0
  134. package/dist/api/compiler/link-tables.d.ts +36 -0
  135. package/dist/api/compiler/link-tables.js +83 -0
  136. package/dist/api/compiler/locale-data.d.ts +24 -0
  137. package/dist/api/compiler/locale-data.js +183 -0
  138. package/dist/api/compiler/locale.d.ts +4 -0
  139. package/dist/api/compiler/locale.js +317 -0
  140. package/dist/api/compiler/locales/cs-CZ.d.ts +2 -0
  141. package/dist/api/compiler/locales/cs-CZ.js +3 -0
  142. package/dist/api/compiler/locales/de-DE.d.ts +2 -0
  143. package/dist/api/compiler/locales/de-DE.js +3 -0
  144. package/dist/api/compiler/locales/es-ES.d.ts +2 -0
  145. package/dist/api/compiler/locales/es-ES.js +3 -0
  146. package/dist/api/compiler/locales/fr-FR.d.ts +2 -0
  147. package/dist/api/compiler/locales/fr-FR.js +3 -0
  148. package/dist/api/compiler/locales/it-IT.d.ts +2 -0
  149. package/dist/api/compiler/locales/it-IT.js +3 -0
  150. package/dist/api/compiler/locales/ja-JP.d.ts +2 -0
  151. package/dist/api/compiler/locales/ja-JP.js +3 -0
  152. package/dist/api/compiler/locales/ko-KR.d.ts +2 -0
  153. package/dist/api/compiler/locales/ko-KR.js +3 -0
  154. package/dist/api/compiler/locales/pl-PL.d.ts +2 -0
  155. package/dist/api/compiler/locales/pl-PL.js +3 -0
  156. package/dist/api/compiler/locales/pt-BR.d.ts +2 -0
  157. package/dist/api/compiler/locales/pt-BR.js +3 -0
  158. package/dist/api/compiler/locales/ru-RU.d.ts +2 -0
  159. package/dist/api/compiler/locales/ru-RU.js +3 -0
  160. package/dist/api/compiler/locales/tr-TR.d.ts +2 -0
  161. package/dist/api/compiler/locales/tr-TR.js +3 -0
  162. package/dist/api/compiler/locales/zh-CN.d.ts +2 -0
  163. package/dist/api/compiler/locales/zh-CN.js +3 -0
  164. package/dist/api/compiler/locales/zh-TW.d.ts +2 -0
  165. package/dist/api/compiler/locales/zh-TW.js +3 -0
  166. package/dist/api/compiler/module-resolution-types.d.ts +83 -0
  167. package/dist/api/compiler/module-resolution-types.js +176 -0
  168. package/dist/api/compiler/module-resolution.d.ts +71 -0
  169. package/dist/api/compiler/module-resolution.js +1598 -0
  170. package/dist/api/compiler/module-specifiers.d.ts +64 -0
  171. package/dist/api/compiler/module-specifiers.js +1101 -0
  172. package/dist/api/compiler/name-resolver.d.ts +43 -0
  173. package/dist/api/compiler/name-resolver.js +509 -0
  174. package/dist/api/compiler/node-builder-names.d.ts +32 -0
  175. package/dist/api/compiler/node-builder-names.js +854 -0
  176. package/dist/api/compiler/node-builder-pseudo.d.ts +36 -0
  177. package/dist/api/compiler/node-builder-pseudo.js +744 -0
  178. package/dist/api/compiler/node-builder-reuse.d.ts +4 -0
  179. package/dist/api/compiler/node-builder-reuse.js +647 -0
  180. package/dist/api/compiler/node-builder.d.ts +270 -0
  181. package/dist/api/compiler/node-builder.js +2645 -0
  182. package/dist/api/compiler/option-declarations.d.ts +90 -0
  183. package/dist/api/compiler/option-declarations.js +1460 -0
  184. package/dist/api/compiler/options.d.ts +289 -0
  185. package/dist/api/compiler/options.js +1197 -0
  186. package/dist/api/compiler/output-paths.d.ts +42 -0
  187. package/dist/api/compiler/output-paths.js +195 -0
  188. package/dist/api/compiler/package-json.d.ts +175 -0
  189. package/dist/api/compiler/package-json.js +1015 -0
  190. package/dist/api/compiler/parallel-parse.d.ts +219 -0
  191. package/dist/api/compiler/parallel-parse.js +537 -0
  192. package/dist/api/compiler/parser.d.ts +587 -0
  193. package/dist/api/compiler/parser.js +6407 -0
  194. package/dist/api/compiler/path.d.ts +91 -0
  195. package/dist/api/compiler/path.js +705 -0
  196. package/dist/api/compiler/printer/async-helpers.d.ts +22 -0
  197. package/dist/api/compiler/printer/async-helpers.js +91 -0
  198. package/dist/api/compiler/printer/auto-generate.d.ts +13 -0
  199. package/dist/api/compiler/printer/auto-generate.js +20 -0
  200. package/dist/api/compiler/printer/decorator-helpers.d.ts +24 -0
  201. package/dist/api/compiler/printer/decorator-helpers.js +118 -0
  202. package/dist/api/compiler/printer/emit-context.d.ts +154 -0
  203. package/dist/api/compiler/printer/emit-context.js +576 -0
  204. package/dist/api/compiler/printer/emit-flags.d.ts +60 -0
  205. package/dist/api/compiler/printer/emit-flags.js +2 -0
  206. package/dist/api/compiler/printer/factory-base.d.ts +171 -0
  207. package/dist/api/compiler/printer/factory-base.js +1505 -0
  208. package/dist/api/compiler/printer/factory.d.ts +147 -0
  209. package/dist/api/compiler/printer/factory.js +542 -0
  210. package/dist/api/compiler/printer/helpers.d.ts +27 -0
  211. package/dist/api/compiler/printer/helpers.js +164 -0
  212. package/dist/api/compiler/printer/name-generator.d.ts +41 -0
  213. package/dist/api/compiler/printer/name-generator.js +283 -0
  214. package/dist/api/compiler/printer/printer.d.ts +411 -0
  215. package/dist/api/compiler/printer/printer.js +4517 -0
  216. package/dist/api/compiler/printer/text-writer.d.ts +46 -0
  217. package/dist/api/compiler/printer/text-writer.js +172 -0
  218. package/dist/api/compiler/printer/utilities.d.ts +82 -0
  219. package/dist/api/compiler/printer/utilities.js +817 -0
  220. package/dist/api/compiler/program-checker.d.ts +156 -0
  221. package/dist/api/compiler/program-checker.js +526 -0
  222. package/dist/api/compiler/program-utilities.d.ts +52 -0
  223. package/dist/api/compiler/program-utilities.js +365 -0
  224. package/dist/api/compiler/program.d.ts +180 -0
  225. package/dist/api/compiler/program.js +1011 -0
  226. package/dist/api/compiler/pseudo-bigint.d.ts +5 -0
  227. package/dist/api/compiler/pseudo-bigint.js +61 -0
  228. package/dist/api/compiler/regexp-checker.d.ts +38 -0
  229. package/dist/api/compiler/regexp-checker.js +942 -0
  230. package/dist/api/compiler/relations.d.ts +263 -0
  231. package/dist/api/compiler/relations.js +4002 -0
  232. package/dist/api/compiler/reparser.d.ts +48 -0
  233. package/dist/api/compiler/reparser.js +1323 -0
  234. package/dist/api/compiler/scanner.d.ts +256 -0
  235. package/dist/api/compiler/scanner.js +2853 -0
  236. package/dist/api/compiler/side-state.d.ts +16 -0
  237. package/dist/api/compiler/side-state.js +89 -0
  238. package/dist/api/compiler/sourcemap.d.ts +55 -0
  239. package/dist/api/compiler/sourcemap.js +340 -0
  240. package/dist/api/compiler/spelling.d.ts +14 -0
  241. package/dist/api/compiler/spelling.js +128 -0
  242. package/dist/api/compiler/symbol-accessibility.d.ts +57 -0
  243. package/dist/api/compiler/symbol-accessibility.js +894 -0
  244. package/dist/api/compiler/symbol.d.ts +240 -0
  245. package/dist/api/compiler/symbol.js +228 -0
  246. package/dist/api/compiler/symlinks.d.ts +32 -0
  247. package/dist/api/compiler/symlinks.js +114 -0
  248. package/dist/api/compiler/syntax-kind.d.ts +389 -0
  249. package/dist/api/compiler/syntax-kind.js +2 -0
  250. package/dist/api/compiler/timeline.d.ts +9 -0
  251. package/dist/api/compiler/timeline.js +54 -0
  252. package/dist/api/compiler/transformers/alias-references.d.ts +39 -0
  253. package/dist/api/compiler/transformers/alias-references.js +676 -0
  254. package/dist/api/compiler/transformers/async-utilities.d.ts +51 -0
  255. package/dist/api/compiler/transformers/async-utilities.js +260 -0
  256. package/dist/api/compiler/transformers/async.d.ts +53 -0
  257. package/dist/api/compiler/transformers/async.js +645 -0
  258. package/dist/api/compiler/transformers/class-fields.d.ts +206 -0
  259. package/dist/api/compiler/transformers/class-fields.js +2418 -0
  260. package/dist/api/compiler/transformers/class-utilities.d.ts +46 -0
  261. package/dist/api/compiler/transformers/class-utilities.js +261 -0
  262. package/dist/api/compiler/transformers/commonjs-module.d.ts +103 -0
  263. package/dist/api/compiler/transformers/commonjs-module.js +1180 -0
  264. package/dist/api/compiler/transformers/const-enum-inliner.d.ts +11 -0
  265. package/dist/api/compiler/transformers/const-enum-inliner.js +36 -0
  266. package/dist/api/compiler/transformers/declarations-diagnostics.d.ts +52 -0
  267. package/dist/api/compiler/transformers/declarations-diagnostics.js +538 -0
  268. package/dist/api/compiler/transformers/declarations-pseudo.d.ts +160 -0
  269. package/dist/api/compiler/transformers/declarations-pseudo.js +797 -0
  270. package/dist/api/compiler/transformers/declarations-resolver.d.ts +152 -0
  271. package/dist/api/compiler/transformers/declarations-resolver.js +35 -0
  272. package/dist/api/compiler/transformers/declarations-syntactic.d.ts +119 -0
  273. package/dist/api/compiler/transformers/declarations-syntactic.js +1582 -0
  274. package/dist/api/compiler/transformers/declarations-tracker.d.ts +46 -0
  275. package/dist/api/compiler/transformers/declarations-tracker.js +197 -0
  276. package/dist/api/compiler/transformers/declarations.d.ts +175 -0
  277. package/dist/api/compiler/transformers/declarations.js +2380 -0
  278. package/dist/api/compiler/transformers/decorator-metadata.d.ts +54 -0
  279. package/dist/api/compiler/transformers/decorator-metadata.js +554 -0
  280. package/dist/api/compiler/transformers/decorator-utilities.d.ts +38 -0
  281. package/dist/api/compiler/transformers/decorator-utilities.js +238 -0
  282. package/dist/api/compiler/transformers/destructuring.d.ts +25 -0
  283. package/dist/api/compiler/transformers/destructuring.js +626 -0
  284. package/dist/api/compiler/transformers/downlevel.d.ts +6 -0
  285. package/dist/api/compiler/transformers/downlevel.js +45 -0
  286. package/dist/api/compiler/transformers/emit-resolver.d.ts +61 -0
  287. package/dist/api/compiler/transformers/emit-resolver.js +197 -0
  288. package/dist/api/compiler/transformers/es-decorators.d.ts +118 -0
  289. package/dist/api/compiler/transformers/es-decorators.js +1901 -0
  290. package/dist/api/compiler/transformers/exponentiation.d.ts +11 -0
  291. package/dist/api/compiler/transformers/exponentiation.js +76 -0
  292. package/dist/api/compiler/transformers/external-module-info.d.ts +35 -0
  293. package/dist/api/compiler/transformers/external-module-info.js +351 -0
  294. package/dist/api/compiler/transformers/for-await.d.ts +43 -0
  295. package/dist/api/compiler/transformers/for-await.js +469 -0
  296. package/dist/api/compiler/transformers/import-elision.d.ts +16 -0
  297. package/dist/api/compiler/transformers/import-elision.js +124 -0
  298. package/dist/api/compiler/transformers/jsx-entities.d.ts +1 -0
  299. package/dist/api/compiler/transformers/jsx-entities.js +256 -0
  300. package/dist/api/compiler/transformers/jsx.d.ts +71 -0
  301. package/dist/api/compiler/transformers/jsx.js +700 -0
  302. package/dist/api/compiler/transformers/legacy-decorators.d.ts +56 -0
  303. package/dist/api/compiler/transformers/legacy-decorators.js +564 -0
  304. package/dist/api/compiler/transformers/logical-assignment.d.ts +14 -0
  305. package/dist/api/compiler/transformers/logical-assignment.js +62 -0
  306. package/dist/api/compiler/transformers/module-utilities.d.ts +9 -0
  307. package/dist/api/compiler/transformers/module-utilities.js +36 -0
  308. package/dist/api/compiler/transformers/module.d.ts +49 -0
  309. package/dist/api/compiler/transformers/module.js +296 -0
  310. package/dist/api/compiler/transformers/named-evaluation.d.ts +26 -0
  311. package/dist/api/compiler/transformers/named-evaluation.js +266 -0
  312. package/dist/api/compiler/transformers/nullish-coalescing.d.ts +9 -0
  313. package/dist/api/compiler/transformers/nullish-coalescing.js +26 -0
  314. package/dist/api/compiler/transformers/object-rest-spread.d.ts +34 -0
  315. package/dist/api/compiler/transformers/object-rest-spread.js +411 -0
  316. package/dist/api/compiler/transformers/optional-catch.d.ts +9 -0
  317. package/dist/api/compiler/transformers/optional-catch.js +20 -0
  318. package/dist/api/compiler/transformers/optional-chain.d.ts +14 -0
  319. package/dist/api/compiler/transformers/optional-chain.js +188 -0
  320. package/dist/api/compiler/transformers/reference-resolver.d.ts +128 -0
  321. package/dist/api/compiler/transformers/reference-resolver.js +1155 -0
  322. package/dist/api/compiler/transformers/runtime-syntax.d.ts +71 -0
  323. package/dist/api/compiler/transformers/runtime-syntax.js +753 -0
  324. package/dist/api/compiler/transformers/subtree-facts.d.ts +9 -0
  325. package/dist/api/compiler/transformers/subtree-facts.js +203 -0
  326. package/dist/api/compiler/transformers/syntax-facts.d.ts +51 -0
  327. package/dist/api/compiler/transformers/syntax-facts.js +254 -0
  328. package/dist/api/compiler/transformers/tagged-template.d.ts +17 -0
  329. package/dist/api/compiler/transformers/tagged-template.js +148 -0
  330. package/dist/api/compiler/transformers/transformer.d.ts +17 -0
  331. package/dist/api/compiler/transformers/transformer.js +54 -0
  332. package/dist/api/compiler/transformers/type-eraser.d.ts +21 -0
  333. package/dist/api/compiler/transformers/type-eraser.js +346 -0
  334. package/dist/api/compiler/transformers/type-serialization.d.ts +20 -0
  335. package/dist/api/compiler/transformers/type-serialization.js +347 -0
  336. package/dist/api/compiler/transformers/using.d.ts +56 -0
  337. package/dist/api/compiler/transformers/using.js +453 -0
  338. package/dist/api/compiler/transformers/utilities.d.ts +50 -0
  339. package/dist/api/compiler/transformers/utilities.js +347 -0
  340. package/dist/api/compiler/transformers/visitor-base.d.ts +6 -0
  341. package/dist/api/compiler/transformers/visitor-base.js +817 -0
  342. package/dist/api/compiler/transformers/visitor-hooks.d.ts +29 -0
  343. package/dist/api/compiler/transformers/visitor-hooks.js +189 -0
  344. package/dist/api/compiler/tsconfig.d.ts +177 -0
  345. package/dist/api/compiler/tsconfig.js +1311 -0
  346. package/dist/api/compiler/type-printer.d.ts +15 -0
  347. package/dist/api/compiler/type-printer.js +74 -0
  348. package/dist/api/compiler/types.d.ts +87 -0
  349. package/dist/api/compiler/types.js +23 -0
  350. package/dist/api/compiler/unicode-identifiers.d.ts +2 -0
  351. package/dist/api/compiler/unicode-identifiers.js +209 -0
  352. package/dist/api/compiler/unicode-properties.d.ts +8 -0
  353. package/dist/api/compiler/unicode-properties.js +531 -0
  354. package/dist/api/compiler/vfs-match.d.ts +24 -0
  355. package/dist/api/compiler/vfs-match.js +587 -0
  356. package/dist/api/library/ast.d.ts +3 -2
  357. package/dist/api/library/ast.generated.d.ts +127 -139
  358. package/dist/api/library/checker.d.ts +51 -0
  359. package/dist/api/library/checker.js +318 -0
  360. package/dist/api/library/diagnostics.d.ts +13 -0
  361. package/dist/api/library/diagnostics.js +50 -0
  362. package/dist/api/library/disk.d.ts +13 -0
  363. package/dist/api/library/disk.js +66 -0
  364. package/dist/api/library/errors.d.ts +13 -0
  365. package/dist/api/library/errors.js +24 -0
  366. package/dist/api/library/host.d.ts +24 -0
  367. package/dist/api/library/host.js +52 -0
  368. package/dist/api/library/index.d.ts +5 -1
  369. package/dist/api/library/index.js +4 -0
  370. package/dist/api/library/nodes.d.ts +51 -0
  371. package/dist/api/library/nodes.js +196 -0
  372. package/dist/api/library/options.d.ts +144 -0
  373. package/dist/api/library/options.js +308 -0
  374. package/dist/api/library/parse.d.ts +19 -0
  375. package/dist/api/library/parse.js +41 -0
  376. package/dist/api/library/program.d.ts +21 -0
  377. package/dist/api/library/program.js +234 -0
  378. package/dist/api/library/types.d.ts +14 -1
  379. package/package.json +12 -8
  380. package/src/compiler/ast-utilities.ts +548 -0
  381. package/src/compiler/ast.ts +12862 -0
  382. package/src/compiler/astnav.ts +799 -0
  383. package/src/compiler/binder-utilities.ts +1392 -0
  384. package/src/compiler/binder.ts +2703 -0
  385. package/src/compiler/build-info.ts +1197 -0
  386. package/src/compiler/character-codes.ts +323 -0
  387. package/src/compiler/checker-calls.ts +2155 -0
  388. package/src/compiler/checker-classes.ts +706 -0
  389. package/src/compiler/checker-contextual.ts +1457 -0
  390. package/src/compiler/checker-declaration-order.ts +438 -0
  391. package/src/compiler/checker-declarations.ts +1194 -0
  392. package/src/compiler/checker-declared-types.ts +919 -0
  393. package/src/compiler/checker-decorators.ts +694 -0
  394. package/src/compiler/checker-deprecation.ts +359 -0
  395. package/src/compiler/checker-destructuring.ts +805 -0
  396. package/src/compiler/checker-elaboration.ts +477 -0
  397. package/src/compiler/checker-emit-helpers.ts +224 -0
  398. package/src/compiler/checker-emit-resolver.ts +769 -0
  399. package/src/compiler/checker-evaluator.ts +243 -0
  400. package/src/compiler/checker-expressions.ts +1831 -0
  401. package/src/compiler/checker-features.ts +361 -0
  402. package/src/compiler/checker-flow.ts +394 -0
  403. package/src/compiler/checker-functions.ts +1296 -0
  404. package/src/compiler/checker-generated-code.ts +227 -0
  405. package/src/compiler/checker-globals.ts +52 -0
  406. package/src/compiler/checker-grammar.ts +3584 -0
  407. package/src/compiler/checker-heritage.ts +1233 -0
  408. package/src/compiler/checker-inference.ts +2576 -0
  409. package/src/compiler/checker-iteration.ts +1206 -0
  410. package/src/compiler/checker-javascript.ts +502 -0
  411. package/src/compiler/checker-jsdoc.ts +360 -0
  412. package/src/compiler/checker-jsx.ts +1924 -0
  413. package/src/compiler/checker-literals.ts +61 -0
  414. package/src/compiler/checker-members.ts +2436 -0
  415. package/src/compiler/checker-modules.ts +2886 -0
  416. package/src/compiler/checker-narrowing.ts +3230 -0
  417. package/src/compiler/checker-object-literals.ts +575 -0
  418. package/src/compiler/checker-operators.ts +1422 -0
  419. package/src/compiler/checker-overloads.ts +328 -0
  420. package/src/compiler/checker-property-access.ts +906 -0
  421. package/src/compiler/checker-services.ts +1149 -0
  422. package/src/compiler/checker-signatures.ts +1032 -0
  423. package/src/compiler/checker-source-file.ts +732 -0
  424. package/src/compiler/checker-statements.ts +292 -0
  425. package/src/compiler/checker-super.ts +261 -0
  426. package/src/compiler/checker-symbol-types.ts +2107 -0
  427. package/src/compiler/checker-symbols.ts +2150 -0
  428. package/src/compiler/checker-type-factory.ts +2579 -0
  429. package/src/compiler/checker-type-nodes.ts +1033 -0
  430. package/src/compiler/checker-type-operators.ts +2502 -0
  431. package/src/compiler/checker-types.ts +2340 -0
  432. package/src/compiler/checker-unused.ts +642 -0
  433. package/src/compiler/checker-utilities.ts +161 -0
  434. package/src/compiler/checker.ts +1116 -0
  435. package/src/compiler/command-line.ts +436 -0
  436. package/src/compiler/compile-program.ts +439 -0
  437. package/src/compiler/decoder.ts +1209 -0
  438. package/src/compiler/diagnostic-locales.ts +86 -0
  439. package/src/compiler/diagnostic-messages.ts +2349 -0
  440. package/src/compiler/diagnostics.ts +897 -0
  441. package/src/compiler/emitter.ts +434 -0
  442. package/src/compiler/encoder.ts +1945 -0
  443. package/src/compiler/file-include.ts +673 -0
  444. package/src/compiler/file-loader.ts +1528 -0
  445. package/src/compiler/file-system.ts +143 -0
  446. package/src/compiler/flow.ts +89 -0
  447. package/src/compiler/help.ts +473 -0
  448. package/src/compiler/incremental.ts +2784 -0
  449. package/src/compiler/init.ts +141 -0
  450. package/src/compiler/instantiation.ts +894 -0
  451. package/src/compiler/jsdoc.ts +1386 -0
  452. package/src/compiler/link-tables.ts +98 -0
  453. package/src/compiler/locale-data.ts +203 -0
  454. package/src/compiler/locale.ts +307 -0
  455. package/src/compiler/locales/cs-CZ.ts +5 -0
  456. package/src/compiler/locales/de-DE.ts +5 -0
  457. package/src/compiler/locales/es-ES.ts +5 -0
  458. package/src/compiler/locales/fr-FR.ts +5 -0
  459. package/src/compiler/locales/it-IT.ts +5 -0
  460. package/src/compiler/locales/ja-JP.ts +5 -0
  461. package/src/compiler/locales/ko-KR.ts +5 -0
  462. package/src/compiler/locales/pl-PL.ts +5 -0
  463. package/src/compiler/locales/pt-BR.ts +5 -0
  464. package/src/compiler/locales/ru-RU.ts +5 -0
  465. package/src/compiler/locales/tr-TR.ts +5 -0
  466. package/src/compiler/locales/zh-CN.ts +5 -0
  467. package/src/compiler/locales/zh-TW.ts +5 -0
  468. package/src/compiler/module-resolution-types.ts +243 -0
  469. package/src/compiler/module-resolution.ts +2072 -0
  470. package/src/compiler/module-specifiers.ts +1491 -0
  471. package/src/compiler/name-resolver.ts +646 -0
  472. package/src/compiler/node-builder-names.ts +1069 -0
  473. package/src/compiler/node-builder-pseudo.ts +892 -0
  474. package/src/compiler/node-builder-reuse.ts +764 -0
  475. package/src/compiler/node-builder.ts +3425 -0
  476. package/src/compiler/option-declarations.ts +1560 -0
  477. package/src/compiler/options.ts +1576 -0
  478. package/src/compiler/output-paths.ts +334 -0
  479. package/src/compiler/package-json.ts +1083 -0
  480. package/src/compiler/parallel-check.ts +1951 -0
  481. package/src/compiler/parallel-parse.ts +590 -0
  482. package/src/compiler/parse-thread.ts +140 -0
  483. package/src/compiler/parser.ts +7716 -0
  484. package/src/compiler/path.ts +717 -0
  485. package/src/compiler/printer/async-helpers.ts +183 -0
  486. package/src/compiler/printer/auto-generate.ts +27 -0
  487. package/src/compiler/printer/decorator-helpers.ts +218 -0
  488. package/src/compiler/printer/emit-context.ts +679 -0
  489. package/src/compiler/printer/emit-flags.ts +64 -0
  490. package/src/compiler/printer/factory-base.ts +2577 -0
  491. package/src/compiler/printer/factory.ts +764 -0
  492. package/src/compiler/printer/helpers.ts +291 -0
  493. package/src/compiler/printer/name-generator.ts +372 -0
  494. package/src/compiler/printer/printer.ts +5072 -0
  495. package/src/compiler/printer/text-writer.ts +183 -0
  496. package/src/compiler/printer/utilities.ts +884 -0
  497. package/src/compiler/program-checker.ts +592 -0
  498. package/src/compiler/program-utilities.ts +435 -0
  499. package/src/compiler/program.ts +1419 -0
  500. package/src/compiler/pseudo-bigint.ts +62 -0
  501. package/src/compiler/regexp-checker.ts +1142 -0
  502. package/src/compiler/relations.ts +5149 -0
  503. package/src/compiler/reparser.ts +1566 -0
  504. package/src/compiler/scanner.ts +2951 -0
  505. package/src/compiler/show-config.ts +239 -0
  506. package/src/compiler/side-state.ts +125 -0
  507. package/src/compiler/sourcemap.ts +366 -0
  508. package/src/compiler/spelling.ts +122 -0
  509. package/src/compiler/symbol-accessibility.ts +1071 -0
  510. package/src/compiler/symbol.ts +439 -0
  511. package/src/compiler/symlinks.ts +137 -0
  512. package/src/compiler/syntax-kind.ts +391 -0
  513. package/src/compiler/thread-entry.ts +191 -0
  514. package/src/compiler/timeline.ts +53 -0
  515. package/src/compiler/transformers/alias-references.ts +757 -0
  516. package/src/compiler/transformers/async-utilities.ts +335 -0
  517. package/src/compiler/transformers/async.ts +838 -0
  518. package/src/compiler/transformers/class-fields.ts +2967 -0
  519. package/src/compiler/transformers/class-utilities.ts +324 -0
  520. package/src/compiler/transformers/commonjs-module.ts +1621 -0
  521. package/src/compiler/transformers/const-enum-inliner.ts +50 -0
  522. package/src/compiler/transformers/declarations-diagnostics.ts +832 -0
  523. package/src/compiler/transformers/declarations-pseudo.ts +966 -0
  524. package/src/compiler/transformers/declarations-resolver.ts +249 -0
  525. package/src/compiler/transformers/declarations-syntactic.ts +1859 -0
  526. package/src/compiler/transformers/declarations-tracker.ts +269 -0
  527. package/src/compiler/transformers/declarations.ts +3120 -0
  528. package/src/compiler/transformers/decorator-metadata.ts +697 -0
  529. package/src/compiler/transformers/decorator-utilities.ts +283 -0
  530. package/src/compiler/transformers/destructuring.ts +708 -0
  531. package/src/compiler/transformers/downlevel.ts +50 -0
  532. package/src/compiler/transformers/emit-resolver.ts +258 -0
  533. package/src/compiler/transformers/es-decorators.ts +2682 -0
  534. package/src/compiler/transformers/exponentiation.ts +80 -0
  535. package/src/compiler/transformers/external-module-info.ts +412 -0
  536. package/src/compiler/transformers/for-await.ts +687 -0
  537. package/src/compiler/transformers/import-elision.ts +152 -0
  538. package/src/compiler/transformers/jsx-entities.ts +256 -0
  539. package/src/compiler/transformers/jsx.ts +824 -0
  540. package/src/compiler/transformers/legacy-decorators.ts +726 -0
  541. package/src/compiler/transformers/logical-assignment.ts +75 -0
  542. package/src/compiler/transformers/module-utilities.ts +42 -0
  543. package/src/compiler/transformers/module.ts +474 -0
  544. package/src/compiler/transformers/named-evaluation.ts +389 -0
  545. package/src/compiler/transformers/nullish-coalescing.ts +35 -0
  546. package/src/compiler/transformers/object-rest-spread.ts +577 -0
  547. package/src/compiler/transformers/optional-catch.ts +29 -0
  548. package/src/compiler/transformers/optional-chain.ts +246 -0
  549. package/src/compiler/transformers/reference-resolver.ts +1201 -0
  550. package/src/compiler/transformers/runtime-syntax.ts +942 -0
  551. package/src/compiler/transformers/subtree-facts.ts +245 -0
  552. package/src/compiler/transformers/syntax-facts.ts +353 -0
  553. package/src/compiler/transformers/tagged-template.ts +167 -0
  554. package/src/compiler/transformers/transformer.ts +56 -0
  555. package/src/compiler/transformers/type-eraser.ts +520 -0
  556. package/src/compiler/transformers/type-serialization.ts +374 -0
  557. package/src/compiler/transformers/using.ts +613 -0
  558. package/src/compiler/transformers/utilities.ts +419 -0
  559. package/src/compiler/transformers/visitor-base.ts +1601 -0
  560. package/src/compiler/transformers/visitor-hooks.ts +252 -0
  561. package/src/compiler/tsc-build.ts +1418 -0
  562. package/src/compiler/tsc-cli.ts +666 -0
  563. package/src/compiler/tsc-compile.ts +437 -0
  564. package/src/compiler/tsc-watch.ts +854 -0
  565. package/src/compiler/tsconfig.ts +1574 -0
  566. package/src/compiler/type-printer.ts +110 -0
  567. package/src/compiler/types.ts +115 -0
  568. package/src/compiler/unicode-identifiers.ts +212 -0
  569. package/src/compiler/unicode-properties.ts +537 -0
  570. package/src/compiler/vfs-match.ts +597 -0
  571. package/src/compiler/xxh3.ts +650 -0
  572. package/src/library/ast.generated.ts +141 -167
  573. package/src/library/ast.ts +4 -1
  574. package/src/library/checker.ts +384 -0
  575. package/src/library/diagnostics.ts +72 -0
  576. package/src/library/disk.ts +73 -0
  577. package/src/library/errors.ts +26 -0
  578. package/src/library/host.ts +63 -0
  579. package/src/library/index.ts +21 -0
  580. package/src/library/nodes.ts +232 -0
  581. package/src/library/options.ts +449 -0
  582. package/src/library/parse.ts +63 -0
  583. package/src/library/program.ts +293 -0
  584. package/src/library/types.ts +14 -1
@@ -0,0 +1,2576 @@
1
+ // Type inference: inference contexts, inferring from source to target types, and the inferred
2
+ // types of type parameters.
3
+ import { sideOf, signatureSideOf } from './side-state.js';
4
+ import {
5
+ type NamedTupleMember,
6
+ type ParameterDeclaration,
7
+ type TypeReferenceNode,
8
+ type MappedTypeNode,
9
+ type Node,
10
+ ModifierFlags,
11
+ NodeFlags,
12
+ type TypeParameterDeclaration,
13
+ type ConditionalTypeNode,
14
+ } from './ast.js';
15
+ import { hasSyntacticModifier } from './binder-utilities.js';
16
+ import { CheckFlags, type Symbol, SymbolFlags, getSymbolId } from './symbol.js';
17
+ import { SyntaxKind } from './syntax-kind.js';
18
+ import type { Checker } from './checker.js';
19
+ import {
20
+ ArrayToSingleTypeMapper,
21
+ type ConditionalRoot,
22
+ type ConditionalType,
23
+ ElementFlags,
24
+ IndexFlags,
25
+ type IndexType,
26
+ type IndexedAccessType,
27
+ type IndexInfo,
28
+ type IntrinsicType,
29
+ type LiteralType,
30
+ type MappedType,
31
+ MergedTypeMapper,
32
+ ObjectFlags,
33
+ type ReverseMappedType,
34
+ type Signature,
35
+ SignatureFlags,
36
+ SignatureKind,
37
+ type StringMappingType,
38
+ type SubstitutionType,
39
+ type TemplateLiteralType,
40
+ Ternary,
41
+ TupleElementInfo,
42
+ type Type,
43
+ TypeFlags,
44
+ TypeMapper,
45
+ type TypeParameter,
46
+ type TypePredicate,
47
+ type TypeReference,
48
+ type UnionOrIntersectionType,
49
+ type UnionType,
50
+ VarianceFlags,
51
+ newTypeMapper,
52
+ SimpleTypeMapper,
53
+ emptyTypes,
54
+ } from './checker-types.js';
55
+ import {
56
+ UnionReduction,
57
+ createAnonymousType,
58
+ createArrayType,
59
+ createArrayTypeEx,
60
+ createTupleType,
61
+ createTupleTypeEx,
62
+ filterType,
63
+ getBaseTypeOfLiteralType,
64
+ getBigIntLiteralType,
65
+ getElementTypes,
66
+ getEndElementCount,
67
+ getIntersectionType,
68
+ getNumberLiteralType,
69
+ getRegularTypeOfLiteralType,
70
+ getStringLiteralType,
71
+ getTemplateLiteralType,
72
+ getTypeArguments,
73
+ getTypeReferenceArity,
74
+ getUnionType,
75
+ getUnionTypeEx,
76
+ getWidenedLiteralType,
77
+ isArrayOrTupleType,
78
+ isErrorType,
79
+ isArrayType,
80
+ isGenericTupleType,
81
+ isLiteralType,
82
+ isMutableArrayOrTuple,
83
+ isReadonlyArrayType,
84
+ isTupleType,
85
+ mapType,
86
+ newIndexInfo,
87
+ newObjectType,
88
+ setStructuredTypeMembers,
89
+ someType,
90
+ tupleTargetOf,
91
+ typesOf,
92
+ } from './checker-type-factory.js';
93
+ import {
94
+ getDeclaredTypeOfClassOrInterface,
95
+ getDeclaredTypeOfSymbol,
96
+ fillMissingTypeArguments,
97
+ getConstraintOfTypeParameter,
98
+ getDefaultFromTypeParameter,
99
+ getMinTypeArgumentCount,
100
+ getDeclaredTypeOfTypeParameter,
101
+ } from './checker-declared-types.js';
102
+ import {
103
+ MappedTypeModifiers,
104
+ applyStringMapping,
105
+ getActualTypeVariable,
106
+ getBranchTypesFromConditionalType,
107
+ getConstraintFromConditionalType,
108
+ getConstraintOfConditionalType,
109
+ getConstraintTypeFromMappedType,
110
+ getElementTypeOfSliceOfTupleType,
111
+ getFalseTypeFromConditionalType,
112
+ getHomomorphicTypeVariable,
113
+ getIndexType,
114
+ getIndexTypeEx,
115
+ getIndexedAccessType,
116
+ getLiteralTypeFromProperty,
117
+ getMappedTypeModifiers,
118
+ getNameTypeFromMappedType,
119
+ getSimplifiedType,
120
+ getSubstitutionIntersection,
121
+ getTemplateTypeFromMappedType,
122
+ getTrueTypeFromConditionalType,
123
+ getTypeParameterFromMappedType,
124
+ isGenericMappedType,
125
+ isNoInferType,
126
+ isTypeMatchedByTemplateLiteralType,
127
+ shouldDeferIndexType,
128
+ } from './checker-type-operators.js';
129
+ import {
130
+ getApparentType,
131
+ getApplicableIndexInfo,
132
+ getBaseConstraintOfType,
133
+ getBaseConstraintOrType,
134
+ getConstraintOfType,
135
+ getIndexInfoOfType,
136
+ getIndexInfosOfType,
137
+ getPropertiesOfObjectType,
138
+ getPropertiesOfType,
139
+ getPropertyOfType,
140
+ getPropertyOfUnionOrIntersectionType,
141
+ getReducedApparentType,
142
+ getReducedType,
143
+ getSignaturesOfType,
144
+ getTypeWithThisArgument,
145
+ isApplicableIndexType,
146
+ isObjectLiteralType,
147
+ } from './checker-members.js';
148
+ import {
149
+ getEffectiveRestType,
150
+ getErasedSignature,
151
+ getParameterCount,
152
+ getRestTypeAtPosition,
153
+ getReturnTypeOfSignature,
154
+ getSignatureInstantiation,
155
+ getThisTypeOfSignature,
156
+ getTypeAtPosition,
157
+ getTypePredicateOfSignature,
158
+ sliceTupleType,
159
+ } from './checker-signatures.js';
160
+ import {
161
+ getNullableType,
162
+ getTypeOfSymbol,
163
+ getWidenedType,
164
+ isReadonlySymbol,
165
+ removeMissingOrUndefinedType,
166
+ removeMissingType,
167
+ } from './checker-symbol-types.js';
168
+ import {
169
+ combineTypeMappers,
170
+ couldContainTypeVariables,
171
+ instantiateSignature,
172
+ instantiateSignatureEx,
173
+ instantiateType,
174
+ instantiateTypes,
175
+ } from './instantiation.js';
176
+ import {
177
+ type TypeComparer,
178
+ ComparerKind,
179
+ getAliasVariances,
180
+ getComparer,
181
+ getUnmatchedProperty,
182
+ getVariances,
183
+ isUnmatchedProperty,
184
+ isDeeplyNestedType,
185
+ setStackEntry,
186
+ isObjectTypeWithInferableIndex,
187
+ isTypeAssignableTo,
188
+ isTypeIdenticalTo,
189
+ isTypeStrictSubtypeOf,
190
+ isTypeSubtypeOf,
191
+ } from './relations.js';
192
+ import { maybeTypeOfKind } from './checker-utilities.js';
193
+ import { getTypeFromTypeNode } from './checker-type-nodes.js';
194
+ import { getMergedSymbol, getSymbolOfDeclaration } from './checker-symbols.js';
195
+ import { parsePseudoBigInt } from './pseudo-bigint.js';
196
+ import { getContextualTypeForInference } from './checker-contextual.js';
197
+
198
+ export const enum InferenceFlags {
199
+ None = 0,
200
+ /** Infer `silentNeverType` for no inferences (otherwise `unknown`). */
201
+ NoDefault = 1 << 0,
202
+ /** Infer `any` for no inferences. */
203
+ AnyDefault = 1 << 1,
204
+ /** A generic function was skipped during inference. */
205
+ SkippedGenericFunction = 1 << 2,
206
+ }
207
+
208
+ export const enum InferencePriority {
209
+ None = 0,
210
+ /** Naked type variable in union or intersection type. */
211
+ NakedTypeVariable = 1 << 0,
212
+ SpeculativeTuple = 1 << 1,
213
+ /** Source originated within a substitution type's substitute. */
214
+ SubstituteSource = 1 << 2,
215
+ HomomorphicMappedType = 1 << 3,
216
+ PartialHomomorphicMappedType = 1 << 4,
217
+ MappedTypeConstraint = 1 << 5,
218
+ ContravariantConditional = 1 << 6,
219
+ /** Inference made from the return type of a generic function. */
220
+ ReturnType = 1 << 7,
221
+ LiteralKeyof = 1 << 8,
222
+ /** Don't infer from constraints of instantiable types. */
223
+ NoConstraints = 1 << 9,
224
+ /** Always use strict rules for contravariant inferences. */
225
+ AlwaysStrict = 1 << 10,
226
+ MaxValue = 1 << 11,
227
+ /** Inference circularity, less than all other priorities. */
228
+ Circularity = -1,
229
+ PriorityImpliesCombination = ReturnType | MappedTypeConstraint | LiteralKeyof,
230
+ }
231
+
232
+ const enum ExpandingFlags {
233
+ None = 0,
234
+ Source = 1,
235
+ Target = 2,
236
+ Both = 3,
237
+ }
238
+
239
+ // Shared empty candidate lists: an InferenceInfo gets its own on its first candidate, as tsgo's nil
240
+ // slices do. Never changed.
241
+ const noCandidates: Type[] = [];
242
+ const noCandidateDepths: number[] = [];
243
+
244
+ /** Inferences for one type parameter. */
245
+ export class InferenceInfo {
246
+ readonly typeParameter: Type;
247
+ /** Covariant candidates, in decreasing depth order. */
248
+ candidates: Type[] = noCandidates;
249
+ candidateDepths: number[] = noCandidateDepths;
250
+ contraCandidates: Type[] = noCandidates;
251
+ inferredType: Type | undefined = undefined;
252
+ priority: InferencePriority = InferencePriority.MaxValue;
253
+ /** Whether all inferences are to top-level occurrences. */
254
+ topLevel = true;
255
+ isFixed = false;
256
+ impliedArity = -1;
257
+
258
+ constructor(typeParameter: Type) {
259
+ this.typeParameter = typeParameter;
260
+ }
261
+
262
+ clone(): InferenceInfo {
263
+ const info = new InferenceInfo(this.typeParameter);
264
+ if (this.candidates.length !== 0) {
265
+ info.candidates = this.candidates.slice();
266
+ info.candidateDepths = this.candidateDepths.slice();
267
+ }
268
+ if (this.contraCandidates.length !== 0) info.contraCandidates = this.contraCandidates.slice();
269
+ info.inferredType = this.inferredType;
270
+ info.priority = this.priority;
271
+ info.topLevel = this.topLevel;
272
+ info.isFixed = this.isFixed;
273
+ info.impliedArity = this.impliedArity;
274
+ return info;
275
+ }
276
+ }
277
+
278
+ export class IntraExpressionInferenceSite {
279
+ readonly node: Node;
280
+ readonly type: Type;
281
+
282
+ constructor(node: Node, type: Type) {
283
+ this.node = node;
284
+ this.type = type;
285
+ }
286
+ }
287
+
288
+ export class InferenceContext {
289
+ inferences: InferenceInfo[];
290
+ /** The generic signature inferences are made for, if any. */
291
+ readonly signature: Signature | undefined;
292
+ flags: InferenceFlags;
293
+ readonly compareTypes: TypeComparer;
294
+ /** Fixes inferences. */
295
+ mapper: TypeMapper;
296
+ nonFixingMapper: TypeMapper;
297
+ /** Maps to inferences from the return type, if any. */
298
+ returnMapper: TypeMapper | undefined = undefined;
299
+ outerReturnMapper: TypeMapper | undefined = undefined;
300
+ inferredTypeParameters: Type[] | undefined = undefined;
301
+ intraExpressionInferenceSites: IntraExpressionInferenceSite[] = [];
302
+
303
+ constructor(
304
+ c: Checker,
305
+ inferences: InferenceInfo[],
306
+ signature: Signature | undefined,
307
+ flags: InferenceFlags,
308
+ compareTypes: TypeComparer,
309
+ ) {
310
+ this.inferences = inferences;
311
+ this.signature = signature;
312
+ this.flags = flags;
313
+ this.compareTypes = compareTypes;
314
+ this.mapper = new InferenceTypeMapper(c, this, true);
315
+ this.nonFixingMapper = new InferenceTypeMapper(c, this, false);
316
+ }
317
+ }
318
+
319
+ /** Maps a context's type parameters to their inferred types, optionally fixing them. */
320
+ export class InferenceTypeMapper extends TypeMapper {
321
+ readonly c: Checker;
322
+ readonly context: InferenceContext;
323
+ readonly fixing: boolean;
324
+
325
+ constructor(c: Checker, context: InferenceContext, fixing: boolean) {
326
+ super();
327
+ this.c = c;
328
+ this.context = context;
329
+ this.fixing = fixing;
330
+ }
331
+
332
+ map(type: Type): Type {
333
+ const inferences = this.context.inferences;
334
+ for (let i = 0; i < inferences.length; i++) {
335
+ const inference = inferences[i]!;
336
+ if (type !== inference.typeParameter) continue;
337
+ if (this.fixing && !inference.isFixed) {
338
+ // Infer from intra-expression sites before committing to an inference.
339
+ inferFromIntraExpressionSites(this.c, this.context);
340
+ clearCachedInferences(inferences);
341
+ inference.isFixed = true;
342
+ }
343
+ return getInferredType(this.c, this.context, i);
344
+ }
345
+ return type;
346
+ }
347
+ }
348
+
349
+ export function createInferenceContext(
350
+ c: Checker,
351
+ typeParameters: readonly Type[],
352
+ signature: Signature | undefined,
353
+ flags: InferenceFlags,
354
+ compareTypes: TypeComparer | undefined,
355
+ ): InferenceContext {
356
+ const inferences: InferenceInfo[] = [];
357
+ for (const tp of typeParameters) inferences.push(new InferenceInfo(tp));
358
+ return new InferenceContext(c, inferences, signature, flags, compareTypes ?? getComparer(c, ComparerKind.Assignable));
359
+ }
360
+
361
+ export function cloneInferenceContext(
362
+ c: Checker,
363
+ context: InferenceContext,
364
+ extraFlags: InferenceFlags,
365
+ ): InferenceContext {
366
+ return new InferenceContext(
367
+ c,
368
+ context.inferences.map((i) => i.clone()),
369
+ context.signature,
370
+ context.flags | extraFlags,
371
+ context.compareTypes,
372
+ );
373
+ }
374
+
375
+ export function cloneInferredPartOfContext(c: Checker, context: InferenceContext): InferenceContext | undefined {
376
+ const inferences: InferenceInfo[] = [];
377
+ for (const i of context.inferences) if (hasInferenceCandidates(i)) inferences.push(i.clone());
378
+ if (inferences.length === 0) return undefined;
379
+ return new InferenceContext(c, inferences, context.signature, context.flags, context.compareTypes);
380
+ }
381
+
382
+ export function getMapperFromContext(context: InferenceContext | undefined): TypeMapper | undefined {
383
+ return context !== undefined ? context.mapper : undefined;
384
+ }
385
+
386
+ /** The context's return mapper combined with a mapper erasing its other type parameters to their current inferences. */
387
+ export function createOuterReturnMapper(c: Checker, context: InferenceContext): TypeMapper {
388
+ if (context.outerReturnMapper === undefined) {
389
+ let mapper: TypeMapper = cloneInferenceContext(c, context, InferenceFlags.None).mapper;
390
+ if (context.returnMapper !== undefined) mapper = new MergedTypeMapper(context.returnMapper, mapper);
391
+ context.outerReturnMapper = mapper;
392
+ }
393
+ return context.outerReturnMapper;
394
+ }
395
+
396
+ export function addIntraExpressionInferenceSite(context: InferenceContext, node: Node, type: Type): void {
397
+ context.intraExpressionInferenceSites.push(new IntraExpressionInferenceSite(node, type));
398
+ }
399
+
400
+ export function clearCachedInferences(inferences: InferenceInfo[]): void {
401
+ for (const inference of inferences) if (!inference.isFixed) inference.inferredType = undefined;
402
+ }
403
+
404
+ export function hasInferenceCandidates(info: InferenceInfo): boolean {
405
+ return info.candidates.length !== 0 || info.contraCandidates.length !== 0;
406
+ }
407
+
408
+ export function hasInferenceCandidatesOrDefault(info: InferenceInfo): boolean {
409
+ return hasInferenceCandidates(info) || hasTypeParameterDefault(info.typeParameter);
410
+ }
411
+
412
+ export function someInferenceHasCandidates(inferences: InferenceInfo[]): boolean {
413
+ for (const info of inferences) if (hasInferenceCandidates(info)) return true;
414
+ return false;
415
+ }
416
+
417
+ export function everyInferenceHasCandidates(inferences: InferenceInfo[]): boolean {
418
+ for (const info of inferences) if (!hasInferenceCandidates(info)) return false;
419
+ return true;
420
+ }
421
+
422
+ export function someInferenceHasCandidatesOrDefault(inferences: InferenceInfo[]): boolean {
423
+ for (const info of inferences) if (hasInferenceCandidatesOrDefault(info)) return true;
424
+ return false;
425
+ }
426
+
427
+ function hasTypeParameterDefault(tp: Type): boolean {
428
+ const symbol = tp.symbol;
429
+ if (symbol === undefined) return false;
430
+ for (const d of symbol.declarations)
431
+ if (d.kind === SyntaxKind.TypeParameter && (d as TypeParameterDeclaration).defaultType !== undefined) return true;
432
+ return false;
433
+ }
434
+
435
+ export function hasOverlappingInferences(a: InferenceInfo[], b: InferenceInfo[]): boolean {
436
+ for (let i = 0; i < a.length; i++) if (hasInferenceCandidates(a[i]!) && hasInferenceCandidates(b[i]!)) return true;
437
+ return false;
438
+ }
439
+
440
+ export function mergeInferences(target: InferenceInfo[], source: InferenceInfo[]): void {
441
+ for (let i = 0; i < target.length; i++)
442
+ if (!hasInferenceCandidates(target[i]!) && hasInferenceCandidates(source[i]!)) target[i] = source[i]!;
443
+ }
444
+
445
+ // ---- Inferring from types
446
+
447
+ /** Infers from `source` to `target` for the type parameters of `inferences`. */
448
+ export function inferTypes(
449
+ c: Checker,
450
+ inferences: InferenceInfo[],
451
+ source: Type,
452
+ target: Type,
453
+ priority: InferencePriority,
454
+ contravariant: boolean,
455
+ ): void {
456
+ const state = new InferenceState(c, inferences, target, priority, contravariant);
457
+ state.inferFromTypes(source, target);
458
+ }
459
+
460
+ const enum InferenceAction {
461
+ ConditionalType,
462
+ GenericMappedTypes,
463
+ ObjectTypes,
464
+ }
465
+
466
+ const enum MatchKind {
467
+ TypeOrBaseIdentical,
468
+ CloselyMatched,
469
+ Identical,
470
+ }
471
+
472
+ class MatchedTypes {
473
+ readonly sources: Type[];
474
+ readonly targets: Type[];
475
+
476
+ constructor(sources: Type[], targets: Type[]) {
477
+ this.sources = sources;
478
+ this.targets = targets;
479
+ }
480
+ }
481
+
482
+ function typesMatch(c: Checker, s: Type, t: Type, kind: MatchKind): boolean {
483
+ switch (kind) {
484
+ case MatchKind.TypeOrBaseIdentical:
485
+ return isTypeOrBaseIdenticalTo(c, s, t);
486
+ case MatchKind.CloselyMatched:
487
+ return isTypeCloselyMatchedBy(s, t);
488
+ case MatchKind.Identical:
489
+ return isTypeIdenticalTo(c, s, t);
490
+ }
491
+ }
492
+
493
+ /** The state of one `inferTypes` walk. */
494
+ class InferenceState {
495
+ readonly c: Checker;
496
+ readonly inferences: InferenceInfo[];
497
+ readonly originalTarget: Type;
498
+ priority: number;
499
+ inferencePriority: number = InferencePriority.MaxValue;
500
+ contravariant: boolean;
501
+ bivariant = false;
502
+ expandingFlags: ExpandingFlags = ExpandingFlags.None;
503
+ propagationType: Type | undefined = undefined;
504
+ /** invokeOnce's pairs by packed type ids (`visitKey`), or spelled when an id is too large to pack. */
505
+ visited: Map<number, InferencePriority> | undefined = undefined;
506
+ visitedSpelled: Map<string, InferencePriority> | undefined = undefined;
507
+ /** invokeOnce's recursion stacks; the first `stackDepth` entries of each are live. */
508
+ readonly sourceStack: Type[] = [];
509
+ readonly targetStack: Type[] = [];
510
+ stackDepth = 0;
511
+ depth = 0;
512
+
513
+ constructor(
514
+ c: Checker,
515
+ inferences: InferenceInfo[],
516
+ originalTarget: Type,
517
+ priority: InferencePriority,
518
+ contravariant: boolean,
519
+ ) {
520
+ this.c = c;
521
+ this.inferences = inferences;
522
+ this.originalTarget = originalTarget;
523
+ this.priority = priority;
524
+ this.contravariant = contravariant;
525
+ }
526
+
527
+ infoFor(t: Type): InferenceInfo | undefined {
528
+ return getInferenceInfoForType(this.inferences, t);
529
+ }
530
+
531
+ inferFromTypes(source: Type, target: Type): void {
532
+ const c = this.c;
533
+ if (!couldContainTypeVariables(c, target) || isNoInferType(c, target)) return;
534
+ if (source === c.wildcardType || source === c.blockedStringType) {
535
+ // Infer the `any`-like source for every type parameter referenced in the target.
536
+ const savePropagationType = this.propagationType;
537
+ this.propagationType = source;
538
+ this.inferFromTypes(target, target);
539
+ this.propagationType = savePropagationType;
540
+ return;
541
+ }
542
+ const sourceAlias = source.alias;
543
+ const targetAlias = target.alias;
544
+ if (sourceAlias !== undefined && targetAlias !== undefined && sourceAlias.symbol === targetAlias.symbol) {
545
+ if (sourceAlias.typeArguments.length !== 0 || targetAlias.typeArguments.length !== 0) {
546
+ // Instantiations of the same alias: infer between the type arguments, with defaults applied.
547
+ const params = c.symbolLinks(sourceAlias.symbol).typeParameters ?? [];
548
+ const minParams = getMinTypeArgumentCount(c, params);
549
+ const sourceTypes = fillMissingTypeArguments(c, sourceAlias.typeArguments, params, minParams, false);
550
+ const targetTypes = fillMissingTypeArguments(c, targetAlias.typeArguments, params, minParams, false);
551
+ this.inferFromTypeArguments(
552
+ sourceTypes,
553
+ targetTypes,
554
+ someTypeCouldHoldInference(c, targetTypes) ? getAliasVariances(c, sourceAlias.symbol) : noVariances,
555
+ );
556
+ }
557
+ return;
558
+ }
559
+ if (source === target && (source.flags & TypeFlags.UnionOrIntersection) !== 0) {
560
+ for (const t of typesOf(source)) this.inferFromTypes(t, t);
561
+ return;
562
+ }
563
+ if ((target.flags & TypeFlags.Union) !== 0) {
564
+ const sourceTypes = (source.flags & TypeFlags.Union) !== 0 ? typesOf(source) : [source];
565
+ // Infer between identically matching constituents, then closely matching ones, removing them.
566
+ const temp = this.inferFromMatchingTypes(sourceTypes, distributedTypes(target), MatchKind.TypeOrBaseIdentical);
567
+ const matched = this.inferFromMatchingTypes(temp.sources, temp.targets, MatchKind.CloselyMatched);
568
+ if (matched.targets.length === 0) return;
569
+ target = getUnionType(c, matched.targets);
570
+ if (matched.sources.length === 0) {
571
+ // Everything matched; infer from the full source at lower priority so that `string` to
572
+ // `string | T` still infers `string` for T.
573
+ this.inferWithPriority(source, target, InferencePriority.NakedTypeVariable);
574
+ return;
575
+ }
576
+ source = getUnionType(c, matched.sources);
577
+ } else if ((target.flags & TypeFlags.Intersection) !== 0 && !everyNonGenericObjectType(c, typesOf(target))) {
578
+ // Reduce intersections unless they're simple combinations of object types.
579
+ if ((source.flags & TypeFlags.Union) === 0) {
580
+ const sourceTypes = (source.flags & TypeFlags.Intersection) !== 0 ? typesOf(source) : [source];
581
+ const matched = this.inferFromMatchingTypes(sourceTypes, typesOf(target), MatchKind.Identical);
582
+ if (matched.sources.length === 0 || matched.targets.length === 0) return;
583
+ source = getIntersectionType(c, matched.sources);
584
+ target = getIntersectionType(c, matched.targets);
585
+ }
586
+ }
587
+ if ((target.flags & (TypeFlags.IndexedAccess | TypeFlags.Substitution)) !== 0) {
588
+ if (isNoInferType(c, target)) return;
589
+ target = getActualTypeVariable(c, target);
590
+ }
591
+ if ((target.flags & TypeFlags.TypeVariable) !== 0) {
592
+ const inference = this.infoFor(target);
593
+ if (inference !== undefined) {
594
+ this.inferToTypeVariable(inference, source, target);
595
+ return;
596
+ }
597
+ // Infer to the simplified indexed access to expose more bare type parameters.
598
+ const simplified = getSimplifiedType(c, target, false);
599
+ if (simplified !== target) this.inferFromTypes(source, simplified);
600
+ else if ((target.flags & TypeFlags.IndexedAccess) !== 0) {
601
+ const access = target as IndexedAccessType;
602
+ const indexType = getSimplifiedType(c, access.indexType, false);
603
+ if ((indexType.flags & TypeFlags.Instantiable) !== 0) {
604
+ const distributed = distributeIndexOverObjectType(
605
+ c,
606
+ getSimplifiedType(c, access.objectType, false),
607
+ indexType,
608
+ );
609
+ if (distributed !== undefined && distributed !== target) this.inferFromTypes(source, distributed);
610
+ }
611
+ }
612
+ }
613
+ if (
614
+ (source.objectFlags & ObjectFlags.Reference) !== 0 &&
615
+ (target.objectFlags & ObjectFlags.Reference) !== 0 &&
616
+ (referenceTarget(source) === referenceTarget(target) || (isArrayType(c, source) && isArrayType(c, target))) &&
617
+ !(referenceNode(source) !== undefined && referenceNode(target) !== undefined)
618
+ ) {
619
+ this.inferFromReferenceTypeArguments(source, target);
620
+ } else if ((source.flags & TypeFlags.Index) !== 0 && (target.flags & TypeFlags.Index) !== 0) {
621
+ this.inferFromContravariantTypes((source as IndexType).target, (target as IndexType).target);
622
+ } else if (
623
+ (isLiteralType(source) || (source.flags & TypeFlags.String) !== 0) &&
624
+ (target.flags & TypeFlags.Index) !== 0
625
+ ) {
626
+ const empty = createEmptyObjectTypeFromStringLiteral(c, source);
627
+ this.inferFromContravariantTypesWithPriority(empty, (target as IndexType).target, InferencePriority.LiteralKeyof);
628
+ } else if ((source.flags & TypeFlags.IndexedAccess) !== 0 && (target.flags & TypeFlags.IndexedAccess) !== 0) {
629
+ this.inferFromTypes((source as IndexedAccessType).objectType, (target as IndexedAccessType).objectType);
630
+ this.inferFromTypes((source as IndexedAccessType).indexType, (target as IndexedAccessType).indexType);
631
+ } else if ((source.flags & TypeFlags.StringMapping) !== 0 && (target.flags & TypeFlags.StringMapping) !== 0) {
632
+ if (source.symbol === target.symbol)
633
+ this.inferFromTypes((source as StringMappingType).target, (target as StringMappingType).target);
634
+ } else if ((source.flags & TypeFlags.Substitution) !== 0) {
635
+ this.inferFromTypes((source as SubstitutionType).baseType, target);
636
+ // Substitutes infer at a lower priority.
637
+ this.inferWithPriority(getSubstitutionIntersection(c, source), target, InferencePriority.SubstituteSource);
638
+ } else if ((target.flags & TypeFlags.Conditional) !== 0) {
639
+ this.invokeOnce(source, target, InferenceAction.ConditionalType);
640
+ } else if ((target.flags & TypeFlags.UnionOrIntersection) !== 0) {
641
+ this.inferToMultipleTypes(source, typesOf(target), target.flags);
642
+ } else if ((source.flags & TypeFlags.Union) !== 0) {
643
+ for (const sourceType of typesOf(source)) this.inferFromTypes(sourceType, target);
644
+ } else if ((target.flags & TypeFlags.TemplateLiteral) !== 0) {
645
+ this.inferToTemplateLiteralType(source, target as TemplateLiteralType);
646
+ } else {
647
+ source = getReducedType(c, source);
648
+ if (isGenericMappedType(c, source) && isGenericMappedType(c, target))
649
+ this.invokeOnce(source, target, InferenceAction.GenericMappedTypes);
650
+ if (
651
+ !(
652
+ (this.priority & InferencePriority.NoConstraints) !== 0 &&
653
+ (source.flags & (TypeFlags.Intersection | TypeFlags.Instantiable)) !== 0
654
+ )
655
+ ) {
656
+ const apparentSource = getApparentType(c, source);
657
+ // The apparent type of an indexed access or conditional may be any type; restart with it.
658
+ if (apparentSource !== source && (apparentSource.flags & (TypeFlags.Object | TypeFlags.Intersection)) === 0) {
659
+ this.inferFromTypes(apparentSource, target);
660
+ return;
661
+ }
662
+ source = apparentSource;
663
+ }
664
+ if ((source.flags & (TypeFlags.Object | TypeFlags.Intersection)) !== 0)
665
+ this.invokeOnce(source, target, InferenceAction.ObjectTypes);
666
+ }
667
+ }
668
+
669
+ inferToTypeVariable(inference: InferenceInfo, source: Type, target: Type): void {
670
+ const c = this.c;
671
+ // Non-inferrable sources are markers that must not become candidates.
672
+ if ((source.objectFlags & ObjectFlags.NonInferrableType) !== 0 || source === c.nonInferrableAnyType) return;
673
+ if (!inference.isFixed) {
674
+ const candidate = this.propagationType ?? source;
675
+ if (candidate === c.blockedStringType) return;
676
+ if (this.priority < inference.priority) {
677
+ inference.candidates = noCandidates;
678
+ inference.candidateDepths = noCandidateDepths;
679
+ inference.contraCandidates = noCandidates;
680
+ inference.topLevel = true;
681
+ inference.priority = this.priority;
682
+ }
683
+ if (this.priority === inference.priority) {
684
+ // Contravariant inferences only in purely contravariant positions.
685
+ if (this.contravariant && !this.bivariant) {
686
+ if (!inference.contraCandidates.includes(candidate)) {
687
+ if (inference.contraCandidates === noCandidates) inference.contraCandidates = [];
688
+ inference.contraCandidates.push(candidate);
689
+ clearCachedInferences(this.inferences);
690
+ }
691
+ } else {
692
+ let index = inference.candidates.indexOf(candidate);
693
+ if (index < 0 || inference.candidateDepths[index] < this.depth) {
694
+ if (index >= 0) {
695
+ inference.candidates.splice(index, 1);
696
+ inference.candidateDepths.splice(index, 1);
697
+ }
698
+ if (inference.candidates === noCandidates) {
699
+ inference.candidates = [];
700
+ inference.candidateDepths = [];
701
+ }
702
+ // Keep candidates with the highest depth first.
703
+ index = 0;
704
+ while (index < inference.candidateDepths.length && inference.candidateDepths[index] >= this.depth) index++;
705
+ inference.candidates.splice(index, 0, candidate);
706
+ inference.candidateDepths.splice(index, 0, this.depth);
707
+ clearCachedInferences(this.inferences);
708
+ }
709
+ }
710
+ }
711
+ if (
712
+ (this.priority & InferencePriority.ReturnType) === 0 &&
713
+ (target.flags & TypeFlags.TypeParameter) !== 0 &&
714
+ inference.topLevel &&
715
+ !isTypeParameterAtTopLevel(c, this.originalTarget, target, 0)
716
+ ) {
717
+ inference.topLevel = false;
718
+ clearCachedInferences(this.inferences);
719
+ }
720
+ }
721
+ this.inferencePriority = Math.min(this.inferencePriority, this.priority);
722
+ }
723
+
724
+ /**
725
+ * Infers between the type arguments of two references to one generic type. The variances only pick
726
+ * the direction of each inference, so they are measured only when a target type argument could hold
727
+ * one: measuring them relates marker instantiations of the whole type.
728
+ */
729
+ inferFromReferenceTypeArguments(source: Type, target: Type): void {
730
+ const c = this.c;
731
+ const sourceTypes = getTypeArguments(c, source);
732
+ const targetTypes = getTypeArguments(c, target);
733
+ this.inferFromTypeArguments(
734
+ sourceTypes,
735
+ targetTypes,
736
+ someTypeCouldHoldInference(c, targetTypes) ? getVariances(c, referenceTarget(source)!) : noVariances,
737
+ );
738
+ }
739
+
740
+ inferFromTypeArguments(sourceTypes: Type[], targetTypes: Type[], variances: VarianceFlags[]): void {
741
+ this.depth++;
742
+ const count = Math.min(sourceTypes.length, targetTypes.length);
743
+ for (let i = 0; i < count; i++) {
744
+ if (i < variances.length && (variances[i] & VarianceFlags.VarianceMask) === VarianceFlags.Contravariant)
745
+ this.inferFromContravariantTypes(sourceTypes[i]!, targetTypes[i]!);
746
+ else this.inferFromTypes(sourceTypes[i]!, targetTypes[i]!);
747
+ }
748
+ this.depth--;
749
+ }
750
+
751
+ inferWithPriority(source: Type, target: Type, newPriority: InferencePriority): void {
752
+ const savePriority = this.priority;
753
+ this.priority |= newPriority;
754
+ this.inferFromTypes(source, target);
755
+ this.priority = savePriority;
756
+ }
757
+
758
+ inferFromContravariantTypesWithPriority(source: Type, target: Type, newPriority: InferencePriority): void {
759
+ const savePriority = this.priority;
760
+ this.priority |= newPriority;
761
+ this.inferFromContravariantTypes(source, target);
762
+ this.priority = savePriority;
763
+ }
764
+
765
+ inferFromContravariantTypes(source: Type, target: Type): void {
766
+ this.contravariant = !this.contravariant;
767
+ this.inferFromTypes(source, target);
768
+ this.contravariant = !this.contravariant;
769
+ }
770
+
771
+ inferFromContravariantTypesIfStrictFunctionTypes(source: Type, target: Type): void {
772
+ if (this.c.strictFunctionTypes || (this.priority & InferencePriority.AlwaysStrict) !== 0)
773
+ this.inferFromContravariantTypes(source, target);
774
+ else this.inferFromTypes(source, target);
775
+ }
776
+
777
+ /** Runs `action` once per source and target pair, stopping at circularities. */
778
+ invokeOnce(source: Type, target: Type, action: InferenceAction): void {
779
+ const key = visitKey(source, target);
780
+ const status = key >= 0 ? this.visited?.get(key) : this.visitedSpelled?.get(source.id + ',' + target.id);
781
+ if (status !== undefined) {
782
+ this.inferencePriority = Math.min(this.inferencePriority, status);
783
+ return;
784
+ }
785
+ this.setVisited(source, target, key, InferencePriority.Circularity);
786
+ const saveInferencePriority = this.inferencePriority;
787
+ this.inferencePriority = InferencePriority.MaxValue;
788
+ // Duplicate recursion identities on both sides mean a circularity.
789
+ const saveExpandingFlags = this.expandingFlags;
790
+ const stackDepth = this.stackDepth;
791
+ setStackEntry(this.sourceStack, stackDepth, source);
792
+ setStackEntry(this.targetStack, stackDepth, target);
793
+ this.stackDepth = stackDepth + 1;
794
+ if (isDeeplyNestedType(this.c, source, this.sourceStack, stackDepth + 1, 2))
795
+ this.expandingFlags |= ExpandingFlags.Source;
796
+ if (isDeeplyNestedType(this.c, target, this.targetStack, stackDepth + 1, 2))
797
+ this.expandingFlags |= ExpandingFlags.Target;
798
+ if (this.expandingFlags !== ExpandingFlags.Both) {
799
+ switch (action) {
800
+ case InferenceAction.ConditionalType:
801
+ this.inferToConditionalType(source, target as ConditionalType);
802
+ break;
803
+ case InferenceAction.GenericMappedTypes:
804
+ this.inferFromGenericMappedTypes(source as MappedType, target as MappedType);
805
+ break;
806
+ case InferenceAction.ObjectTypes:
807
+ this.inferFromObjectTypes(source, target);
808
+ break;
809
+ }
810
+ } else this.inferencePriority = InferencePriority.Circularity;
811
+ this.stackDepth = stackDepth;
812
+ this.expandingFlags = saveExpandingFlags;
813
+ this.setVisited(source, target, key, this.inferencePriority);
814
+ this.inferencePriority = Math.min(this.inferencePriority, saveInferencePriority);
815
+ }
816
+
817
+ setVisited(source: Type, target: Type, key: number, status: InferencePriority): void {
818
+ if (key >= 0) {
819
+ let visited = this.visited;
820
+ if (visited === undefined) {
821
+ visited = new Map<number, InferencePriority>();
822
+ this.visited = visited;
823
+ }
824
+ visited.set(key, status);
825
+ } else {
826
+ let visited = this.visitedSpelled;
827
+ if (visited === undefined) {
828
+ visited = new Map<string, InferencePriority>();
829
+ this.visitedSpelled = visited;
830
+ }
831
+ visited.set(source.id + ',' + target.id, status);
832
+ }
833
+ }
834
+
835
+ inferFromMatchingTypes(sources: Type[], targets: Type[], kind: MatchKind): MatchedTypes {
836
+ const c = this.c;
837
+ const matchedSources: Type[] = [];
838
+ const matchedTargets: Type[] = [];
839
+ for (const t of targets)
840
+ for (const s of sources)
841
+ if (typesMatch(c, s, t, kind)) {
842
+ this.inferFromTypes(s, t);
843
+ if (!matchedSources.includes(s)) matchedSources.push(s);
844
+ if (!matchedTargets.includes(t)) matchedTargets.push(t);
845
+ }
846
+ return new MatchedTypes(
847
+ matchedSources.length !== 0 ? sources.filter((t) => !matchedSources.includes(t)) : sources,
848
+ matchedTargets.length !== 0 ? targets.filter((t) => !matchedTargets.includes(t)) : targets,
849
+ );
850
+ }
851
+
852
+ inferToMultipleTypes(source: Type, targets: Type[], targetFlags: TypeFlags): void {
853
+ let typeVariableCount = 0;
854
+ if ((targetFlags & TypeFlags.Union) !== 0) {
855
+ let nakedTypeVariable: Type | undefined = undefined;
856
+ const sources = (source.flags & TypeFlags.Union) !== 0 ? typesOf(source) : [source];
857
+ const matched: boolean[] = [];
858
+ for (let i = 0; i < sources.length; i++) matched.push(false);
859
+ let inferenceCircularity = false;
860
+ // Infer to targets that aren't naked type variables first, tracking which sources produced
861
+ // inferences of the same quality as a naked type variable would get.
862
+ for (const t of targets) {
863
+ if (this.infoFor(t) !== undefined) {
864
+ nakedTypeVariable = t;
865
+ typeVariableCount++;
866
+ } else
867
+ for (let i = 0; i < sources.length; i++) {
868
+ const saveInferencePriority = this.inferencePriority;
869
+ this.inferencePriority = InferencePriority.MaxValue;
870
+ this.inferFromTypes(sources[i]!, t);
871
+ if (this.inferencePriority === this.priority) matched[i] = true;
872
+ inferenceCircularity = inferenceCircularity || this.inferencePriority === InferencePriority.Circularity;
873
+ this.inferencePriority = Math.min(this.inferencePriority, saveInferencePriority);
874
+ }
875
+ }
876
+ if (typeVariableCount === 0) {
877
+ // Infer `A | B` for T from `A | B` to `T & (X | Y)`.
878
+ const intersectionTypeVariable = this.getSingleTypeVariableFromIntersectionTypes(targets);
879
+ if (intersectionTypeVariable !== undefined)
880
+ this.inferWithPriority(source, intersectionTypeVariable, InferencePriority.NakedTypeVariable);
881
+ return;
882
+ }
883
+ // With a single naked type variable and no circularities, infer the unmatched sources to it.
884
+ if (typeVariableCount === 1 && !inferenceCircularity) {
885
+ const unmatched: Type[] = [];
886
+ for (let i = 0; i < sources.length; i++) if (!matched[i]) unmatched.push(sources[i]!);
887
+ if (unmatched.length !== 0) {
888
+ this.inferFromTypes(getUnionType(this.c, unmatched), nakedTypeVariable!);
889
+ return;
890
+ }
891
+ }
892
+ } else {
893
+ // Inferences from nested naked type variables come first among the candidates.
894
+ for (const t of targets) {
895
+ if (this.infoFor(t) !== undefined) typeVariableCount++;
896
+ else this.inferFromTypes(source, t);
897
+ }
898
+ }
899
+ // Inferences directly to naked type variables get lower priority.
900
+ if (
901
+ ((targetFlags & TypeFlags.Intersection) !== 0 && typeVariableCount === 1) ||
902
+ ((targetFlags & TypeFlags.Intersection) === 0 && typeVariableCount > 0)
903
+ )
904
+ for (const t of targets)
905
+ if (this.infoFor(t) !== undefined) this.inferWithPriority(source, t, InferencePriority.NakedTypeVariable);
906
+ }
907
+
908
+ getSingleTypeVariableFromIntersectionTypes(types: Type[]): Type | undefined {
909
+ let typeVariable: Type | undefined = undefined;
910
+ for (const t of types) {
911
+ if ((t.flags & TypeFlags.Intersection) === 0) return undefined;
912
+ let v: Type | undefined;
913
+ for (const u of typesOf(t)) {
914
+ if (this.infoFor(u) !== undefined) {
915
+ v = u;
916
+ break;
917
+ }
918
+ }
919
+ if (v === undefined || (typeVariable !== undefined && v !== typeVariable)) return undefined;
920
+ typeVariable = v;
921
+ }
922
+ return typeVariable;
923
+ }
924
+
925
+ inferToConditionalType(source: Type, target: ConditionalType): void {
926
+ const c = this.c;
927
+ if ((source.flags & TypeFlags.Conditional) !== 0) {
928
+ const s = source as ConditionalType;
929
+ this.inferFromTypes(s.checkType, target.checkType);
930
+ this.inferFromTypes(s.extendsType, target.extendsType);
931
+ this.inferFromTypes(getTrueTypeFromConditionalType(c, s), getTrueTypeFromConditionalType(c, target));
932
+ this.inferFromTypes(getFalseTypeFromConditionalType(c, s), getFalseTypeFromConditionalType(c, target));
933
+ } else {
934
+ const savePriority = this.priority;
935
+ this.priority |= this.contravariant ? InferencePriority.ContravariantConditional : 0;
936
+ this.inferToMultipleTypes(source, getBranchTypesFromConditionalType(c, target), target.flags);
937
+ this.priority = savePriority;
938
+ }
939
+ }
940
+
941
+ inferToTemplateLiteralType(source: Type, target: TemplateLiteralType): void {
942
+ const c = this.c;
943
+ const matches = inferTypesFromTemplateLiteralType(c, source, target);
944
+ const types = target.types;
945
+ // When the target has only placeholders and nothing matches, infer `never` for each so that
946
+ // instantiation produces `never` rather than collapsing to the constraint.
947
+ if (matches === undefined && !target.texts.every((s) => s === '')) return;
948
+ for (let i = 0; i < types.length; i++) {
949
+ const placeholder = types[i]!;
950
+ const matchSource = matches !== undefined ? matches[i]! : c.neverType;
951
+ if ((matchSource.flags & TypeFlags.StringLiteral) !== 0 && (placeholder.flags & TypeFlags.TypeVariable) !== 0) {
952
+ const info = this.infoFor(placeholder);
953
+ if (info !== undefined) {
954
+ const constraint = getBaseConstraintOfType(c, info.typeParameter);
955
+ if (constraint !== undefined && (constraint.flags & TypeFlags.Any) === 0) {
956
+ const matching = getTemplatePlaceholderInference(c, matchSource as LiteralType, constraint);
957
+ if (matching !== undefined) {
958
+ this.inferFromTypes(matching, placeholder);
959
+ continue;
960
+ }
961
+ }
962
+ }
963
+ }
964
+ this.inferFromTypes(matchSource, placeholder);
965
+ }
966
+ }
967
+
968
+ inferFromGenericMappedTypes(source: MappedType, target: MappedType): void {
969
+ // From `{ [P in S]: X }` to `{ [P in T]: Y }`, infer from S to T and from X to Y.
970
+ const c = this.c;
971
+ this.inferFromTypes(getConstraintTypeFromMappedType(c, source), getConstraintTypeFromMappedType(c, target));
972
+ this.inferFromTypes(getTemplateTypeFromMappedType(c, source), getTemplateTypeFromMappedType(c, target));
973
+ const sourceNameType = getNameTypeFromMappedType(c, source);
974
+ const targetNameType = getNameTypeFromMappedType(c, target);
975
+ if (sourceNameType !== undefined && targetNameType !== undefined)
976
+ this.inferFromTypes(sourceNameType, targetNameType);
977
+ }
978
+
979
+ inferFromObjectTypes(source: Type, target: Type): void {
980
+ const c = this.c;
981
+ if (
982
+ (source.objectFlags & ObjectFlags.Reference) !== 0 &&
983
+ (target.objectFlags & ObjectFlags.Reference) !== 0 &&
984
+ (referenceTarget(source) === referenceTarget(target) || (isArrayType(c, source) && isArrayType(c, target)))
985
+ ) {
986
+ this.inferFromReferenceTypeArguments(source, target);
987
+ return;
988
+ }
989
+ if (isGenericMappedType(c, source) && isGenericMappedType(c, target))
990
+ this.inferFromGenericMappedTypes(source as MappedType, target as MappedType);
991
+ if ((target.objectFlags & ObjectFlags.Mapped) !== 0 && !hasMappedNameType(target as MappedType)) {
992
+ const constraintType = getConstraintTypeFromMappedType(c, target as MappedType);
993
+ if (this.inferToMappedType(source, target as MappedType, constraintType)) return;
994
+ }
995
+ // Infer from members only when the types are possibly related.
996
+ if (typesDefinitelyUnrelated(c, source, target)) return;
997
+ if (isArrayOrTupleType(c, source)) {
998
+ if (isTupleType(target)) {
999
+ this.inferFromTupleTypes(source, target);
1000
+ return;
1001
+ }
1002
+ if (isArrayType(c, target)) {
1003
+ this.inferFromIndexTypes(source, target);
1004
+ return;
1005
+ }
1006
+ }
1007
+ this.inferFromProperties(source, target);
1008
+ this.inferFromSignatures(source, target, SignatureKind.Call);
1009
+ this.inferFromSignatures(source, target, SignatureKind.Construct);
1010
+ this.inferFromIndexTypes(source, target);
1011
+ }
1012
+
1013
+ inferFromTupleTypes(source: Type, target: Type): void {
1014
+ const c = this.c;
1015
+ const sourceArity = getTypeReferenceArity(source);
1016
+ const targetArity = getTypeReferenceArity(target);
1017
+ const elementTypes = getTypeArguments(c, target);
1018
+ const targetTuple = tupleTargetOf(target);
1019
+ const elementInfos = targetTuple.elementInfos;
1020
+ const sourceTypes = getTypeArguments(c, source);
1021
+ // Tuples of the same structure: infer between the element types.
1022
+ if (isTupleType(source) && isTupleTypeStructureMatching(source, target)) {
1023
+ for (let i = 0; i < targetArity; i++) this.inferFromTypes(sourceTypes[i]!, elementTypes[i]!);
1024
+ return;
1025
+ }
1026
+ let startLength = 0;
1027
+ let endLength = 0;
1028
+ if (isTupleType(source)) {
1029
+ const sourceTuple = tupleTargetOf(source);
1030
+ startLength = Math.min(sourceTuple.fixedLength, targetTuple.fixedLength);
1031
+ if ((targetTuple.combinedFlags & ElementFlags.Variable) !== 0)
1032
+ endLength = Math.min(
1033
+ getEndElementCount(sourceTuple, ElementFlags.Fixed),
1034
+ getEndElementCount(targetTuple, ElementFlags.Fixed),
1035
+ );
1036
+ }
1037
+ for (let i = 0; i < startLength; i++) this.inferFromTypes(sourceTypes[i]!, elementTypes[i]!);
1038
+ if (
1039
+ !isTupleType(source) ||
1040
+ (sourceArity - startLength - endLength === 1 &&
1041
+ (tupleTargetOf(source).elementInfos[startLength]!.flags & ElementFlags.Rest) !== 0)
1042
+ ) {
1043
+ // A single rest element remains in the source; infer from it to every middle target element.
1044
+ const restType = sourceTypes[startLength]!;
1045
+ for (let i = startLength; i < targetArity - endLength; i++)
1046
+ this.inferFromTypes(
1047
+ (elementInfos[i]!.flags & ElementFlags.Variadic) !== 0 ? createArrayType(c, restType) : restType,
1048
+ elementTypes[i]!,
1049
+ );
1050
+ } else {
1051
+ const middleLength = targetArity - startLength - endLength;
1052
+ if (middleLength === 2) {
1053
+ const first = elementInfos[startLength]!.flags;
1054
+ const second = elementInfos[startLength + 1]!.flags;
1055
+ if ((first & second & ElementFlags.Variadic) !== 0) {
1056
+ // [...T, ...U]: slice the source by the implied arity of T.
1057
+ const targetInfo = this.infoFor(elementTypes[startLength]!);
1058
+ if (targetInfo !== undefined && targetInfo.impliedArity >= 0) {
1059
+ this.inferFromTypes(
1060
+ sliceTupleType(c, source, startLength, endLength + sourceArity - targetInfo.impliedArity),
1061
+ elementTypes[startLength]!,
1062
+ );
1063
+ this.inferFromTypes(
1064
+ sliceTupleType(c, source, startLength + targetInfo.impliedArity, endLength),
1065
+ elementTypes[startLength + 1]!,
1066
+ );
1067
+ }
1068
+ } else if ((first & ElementFlags.Variadic) !== 0 && (second & ElementFlags.Rest) !== 0) {
1069
+ // [...T, ...rest]: use the arity of a fixed-size tuple constraint of T.
1070
+ const info = this.infoFor(elementTypes[startLength]!);
1071
+ if (info !== undefined) {
1072
+ const constraint = getBaseConstraintOfType(c, info.typeParameter);
1073
+ if (
1074
+ constraint !== undefined &&
1075
+ isTupleType(constraint) &&
1076
+ (tupleTargetOf(constraint).combinedFlags & ElementFlags.Variable) === 0
1077
+ ) {
1078
+ const impliedArity = tupleTargetOf(constraint).fixedLength;
1079
+ this.inferFromTypes(
1080
+ sliceTupleType(c, source, startLength, sourceArity - (startLength + impliedArity)),
1081
+ elementTypes[startLength]!,
1082
+ );
1083
+ const restType = getElementTypeOfSliceOfTupleType(
1084
+ c,
1085
+ source,
1086
+ startLength + impliedArity,
1087
+ endLength,
1088
+ false,
1089
+ false,
1090
+ );
1091
+ if (restType !== undefined) this.inferFromTypes(restType, elementTypes[startLength + 1]!);
1092
+ }
1093
+ }
1094
+ } else if ((first & ElementFlags.Rest) !== 0 && (second & ElementFlags.Variadic) !== 0) {
1095
+ // [...rest, ...T]: use the arity of a fixed-size tuple constraint of T.
1096
+ const info = this.infoFor(elementTypes[startLength + 1]!);
1097
+ if (info !== undefined) {
1098
+ const constraint = getBaseConstraintOfType(c, info.typeParameter);
1099
+ if (
1100
+ constraint !== undefined &&
1101
+ isTupleType(constraint) &&
1102
+ (tupleTargetOf(constraint).combinedFlags & ElementFlags.Variable) === 0
1103
+ ) {
1104
+ const impliedArity = tupleTargetOf(constraint).fixedLength;
1105
+ const endIndex = sourceArity - getEndElementCount(targetTuple, ElementFlags.Fixed);
1106
+ const startIndex = endIndex - impliedArity;
1107
+ if (startIndex >= startLength) {
1108
+ const trailingSlice = createTupleTypeEx(
1109
+ c,
1110
+ sourceTypes.slice(startIndex, endIndex),
1111
+ tupleTargetOf(source).elementInfos.slice(startIndex, endIndex),
1112
+ false,
1113
+ );
1114
+ const restType = getElementTypeOfSliceOfTupleType(
1115
+ c,
1116
+ source,
1117
+ startLength,
1118
+ endLength + impliedArity,
1119
+ false,
1120
+ false,
1121
+ );
1122
+ if (restType !== undefined) this.inferFromTypes(restType, elementTypes[startLength]!);
1123
+ this.inferFromTypes(trailingSlice, elementTypes[startLength + 1]!);
1124
+ }
1125
+ }
1126
+ }
1127
+ }
1128
+ } else if (middleLength === 1 && (elementInfos[startLength]!.flags & ElementFlags.Variadic) !== 0) {
1129
+ // One variadic middle element: infer the source slice between the fixed parts, speculatively
1130
+ // when the target ends in optional elements.
1131
+ const priority =
1132
+ (elementInfos[targetArity - 1]!.flags & ElementFlags.Optional) !== 0
1133
+ ? InferencePriority.SpeculativeTuple
1134
+ : InferencePriority.None;
1135
+ this.inferWithPriority(sliceTupleType(c, source, startLength, endLength), elementTypes[startLength]!, priority);
1136
+ } else if (middleLength === 1 && (elementInfos[startLength]!.flags & ElementFlags.Rest) !== 0) {
1137
+ // One rest middle element: infer the union of the middle source elements.
1138
+ const restType = getElementTypeOfSliceOfTupleType(c, source, startLength, endLength, false, false);
1139
+ if (restType !== undefined) this.inferFromTypes(restType, elementTypes[startLength]!);
1140
+ }
1141
+ }
1142
+ for (let i = 0; i < endLength; i++)
1143
+ this.inferFromTypes(sourceTypes[sourceArity - i - 1]!, elementTypes[targetArity - i - 1]!);
1144
+ }
1145
+
1146
+ inferFromProperties(source: Type, target: Type): void {
1147
+ const c = this.c;
1148
+ for (const targetProp of getPropertiesOfObjectType(c, target)) {
1149
+ const sourceProp = getPropertyOfType(c, source, targetProp.name);
1150
+ if (sourceProp !== undefined)
1151
+ this.inferFromTypes(
1152
+ removeMissingType(c, getTypeOfSymbol(c, sourceProp), (sourceProp.flags & SymbolFlags.Optional) !== 0),
1153
+ removeMissingType(c, getTypeOfSymbol(c, targetProp), (targetProp.flags & SymbolFlags.Optional) !== 0),
1154
+ );
1155
+ }
1156
+ }
1157
+
1158
+ inferFromSignatures(source: Type, target: Type, kind: SignatureKind): void {
1159
+ const c = this.c;
1160
+ const sourceSignatures = getSignaturesOfType(c, source, kind);
1161
+ const sourceLen = sourceSignatures.length;
1162
+ if (sourceLen === 0) return;
1163
+ // Match signatures from the bottom up; excess targets infer from the first source signature.
1164
+ const targetSignatures = getSignaturesOfType(c, target, kind);
1165
+ const targetLen = targetSignatures.length;
1166
+ for (let i = 0; i < targetLen; i++) {
1167
+ const sourceIndex = Math.max(sourceLen - targetLen + i, 0);
1168
+ this.inferFromSignature(
1169
+ getBaseSignature(c, sourceSignatures[sourceIndex]!),
1170
+ getErasedSignature(c, targetSignatures[i]!),
1171
+ );
1172
+ }
1173
+ }
1174
+
1175
+ inferFromSignature(source: Signature, target: Signature): void {
1176
+ const c = this.c;
1177
+ if ((source.flags & SignatureFlags.IsNonInferrable) === 0) {
1178
+ const saveBivariant = this.bivariant;
1179
+ const kind = target.declaration !== undefined ? target.declaration.kind : SyntaxKind.Unknown;
1180
+ // Once in a bivariant signature, nested inferences stay bivariant.
1181
+ this.bivariant =
1182
+ this.bivariant ||
1183
+ kind === SyntaxKind.MethodDeclaration ||
1184
+ kind === SyntaxKind.MethodSignature ||
1185
+ kind === SyntaxKind.Constructor;
1186
+ applyToParameterTypes(c, source, target, (s, t) => this.inferFromContravariantTypesIfStrictFunctionTypes(s, t));
1187
+ this.bivariant = saveBivariant;
1188
+ }
1189
+ applyToReturnTypes(c, source, target, (s, t) => this.inferFromTypes(s, t));
1190
+ }
1191
+
1192
+ inferFromIndexTypes(source: Type, target: Type): void {
1193
+ const c = this.c;
1194
+ // Inferences across mapped type index signatures are like inferences to homomorphic variables.
1195
+ const priority =
1196
+ (source.objectFlags & target.objectFlags & ObjectFlags.Mapped) !== 0
1197
+ ? InferencePriority.HomomorphicMappedType
1198
+ : InferencePriority.None;
1199
+ const indexInfos = getIndexInfosOfType(c, target);
1200
+ if (isObjectTypeWithInferableIndex(c, source))
1201
+ for (const targetInfo of indexInfos) {
1202
+ const propTypes: Type[] = [];
1203
+ for (const prop of getPropertiesOfType(c, source))
1204
+ if (
1205
+ isApplicableIndexType(
1206
+ c,
1207
+ getLiteralTypeFromProperty(c, prop, TypeFlags.StringOrNumberLiteralOrUnique, false),
1208
+ targetInfo.keyType,
1209
+ )
1210
+ ) {
1211
+ const propType = getTypeOfSymbol(c, prop);
1212
+ propTypes.push(
1213
+ (prop.flags & SymbolFlags.Optional) !== 0 ? removeMissingOrUndefinedType(c, propType) : propType,
1214
+ );
1215
+ }
1216
+ for (const info of getIndexInfosOfType(c, source))
1217
+ if (isApplicableIndexType(c, info.keyType, targetInfo.keyType)) propTypes.push(info.valueType);
1218
+ if (propTypes.length !== 0) this.inferWithPriority(getUnionType(c, propTypes), targetInfo.valueType, priority);
1219
+ }
1220
+ for (const targetInfo of indexInfos) {
1221
+ const sourceInfo = getApplicableIndexInfo(c, source, targetInfo.keyType);
1222
+ if (sourceInfo !== undefined) this.inferWithPriority(sourceInfo.valueType, targetInfo.valueType, priority);
1223
+ }
1224
+ }
1225
+
1226
+ inferToMappedType(source: Type, target: MappedType, constraintType: Type): boolean {
1227
+ const c = this.c;
1228
+ if ((constraintType.flags & TypeFlags.UnionOrIntersection) !== 0) {
1229
+ let result = false;
1230
+ for (const t of typesOf(constraintType)) result = this.inferToMappedType(source, target, t) || result;
1231
+ return result;
1232
+ }
1233
+ if ((constraintType.flags & TypeFlags.Index) !== 0) {
1234
+ // From S to a homomorphic `{ [P in keyof T]: X }`: reverse-map S and make a secondary
1235
+ // inference to T, so direct inferences to T win over ones to `Partial<T>`.
1236
+ const inference = this.infoFor((constraintType as IndexType).target);
1237
+ if (inference !== undefined && !inference.isFixed) {
1238
+ const inferredType = inferTypeForHomomorphicMappedType(c, source, target, constraintType as IndexType);
1239
+ if (inferredType !== undefined)
1240
+ this.inferWithPriority(
1241
+ inferredType,
1242
+ inference.typeParameter,
1243
+ (source.objectFlags & ObjectFlags.NonInferrableType) !== 0
1244
+ ? InferencePriority.PartialHomomorphicMappedType
1245
+ : InferencePriority.HomomorphicMappedType,
1246
+ );
1247
+ }
1248
+ return true;
1249
+ }
1250
+ if ((constraintType.flags & TypeFlags.TypeParameter) !== 0) {
1251
+ // From S to `{ [P in K]: X }`: infer `keyof S` to K, then to K's constraint like a homomorphic
1252
+ // mapped type (for `Pick<T, K>`).
1253
+ this.inferWithPriority(
1254
+ getIndexTypeEx(c, source, c.patternForType.has(source) ? IndexFlags.NoIndexSignatures : IndexFlags.None),
1255
+ constraintType,
1256
+ InferencePriority.MappedTypeConstraint,
1257
+ );
1258
+ const extendedConstraint = getConstraintOfType(c, constraintType);
1259
+ if (extendedConstraint !== undefined && this.inferToMappedType(source, target, extendedConstraint)) return true;
1260
+ // Otherwise infer the union of the source's property types to X.
1261
+ const types: Type[] = [];
1262
+ for (const p of getPropertiesOfType(c, source)) types.push(getTypeOfSymbol(c, p));
1263
+ for (const info of getIndexInfosOfType(c, source))
1264
+ types.push(info !== c.enumNumberIndexInfo ? info.valueType : c.neverType);
1265
+ this.inferFromTypes(getUnionType(c, types), getTemplateTypeFromMappedType(c, target));
1266
+ return true;
1267
+ }
1268
+ return false;
1269
+ }
1270
+ }
1271
+
1272
+ // ---- Helpers
1273
+
1274
+ function getInferenceInfoForType(inferences: InferenceInfo[], t: Type): InferenceInfo | undefined {
1275
+ if ((t.flags & TypeFlags.TypeVariable) !== 0)
1276
+ for (const inference of inferences) if (t === inference.typeParameter) return inference;
1277
+ return undefined;
1278
+ }
1279
+
1280
+ function distributedTypes(t: Type): Type[] {
1281
+ return (t.flags & TypeFlags.Union) !== 0 ? typesOf(t) : [t];
1282
+ }
1283
+
1284
+ function referenceTarget(t: Type): Type | undefined {
1285
+ return (t as TypeReference).target;
1286
+ }
1287
+
1288
+ function referenceNode(t: Type): Node | undefined {
1289
+ return (t as TypeReference).node;
1290
+ }
1291
+
1292
+ const noVariances: VarianceFlags[] = [];
1293
+
1294
+ /** Whether inferring to one of `targets` could record a candidate. */
1295
+ function someTypeCouldHoldInference(c: Checker, targets: readonly Type[]): boolean {
1296
+ for (const t of targets) if (couldHoldInference(c, t, 0)) return true;
1297
+ return false;
1298
+ }
1299
+
1300
+ /**
1301
+ * `couldContainTypeVariables` without two of its conservative answers: a deferred reference without an
1302
+ * alias, once its type arguments are resolved, holds type variables only through them, like any other
1303
+ * reference; and the static side of a class declared at the top level of a file or module holds none
1304
+ * outside its generic signatures, which inference erases.
1305
+ */
1306
+ function couldHoldInference(c: Checker, t: Type, depth: number): boolean {
1307
+ if (!couldContainTypeVariables(c, t)) return false;
1308
+ if (t.alias !== undefined || depth === 4) return true;
1309
+ if ((t.objectFlags & ObjectFlags.Reference) !== 0) {
1310
+ const resolved = (t as TypeReference).resolvedTypeArguments ?? sideOf(c, t as TypeReference).resolvedTypeArguments;
1311
+ if (resolved === undefined) return true;
1312
+ for (const a of resolved) if (couldHoldInference(c, a, depth + 1)) return true;
1313
+ return false;
1314
+ }
1315
+ return !isTopLevelClassStaticSide(t);
1316
+ }
1317
+
1318
+ function isTopLevelClassStaticSide(t: Type): boolean {
1319
+ const symbol = t.symbol;
1320
+ if (
1321
+ (t.objectFlags & ObjectFlags.Anonymous) === 0 ||
1322
+ symbol === undefined ||
1323
+ (symbol.flags & SymbolFlags.Class) === 0 ||
1324
+ (symbol.flags &
1325
+ (SymbolFlags.Function | SymbolFlags.Method | SymbolFlags.TypeLiteral | SymbolFlags.ObjectLiteral)) !==
1326
+ 0 ||
1327
+ symbol.declarations.length === 0
1328
+ )
1329
+ return false;
1330
+ for (const d of symbol.declarations) {
1331
+ if (
1332
+ d.kind !== SyntaxKind.ClassDeclaration &&
1333
+ d.kind !== SyntaxKind.InterfaceDeclaration &&
1334
+ d.kind !== SyntaxKind.ModuleDeclaration
1335
+ )
1336
+ return false;
1337
+ for (let n = d.parent!; n.kind !== SyntaxKind.SourceFile; n = n.parent!)
1338
+ if (n.kind !== SyntaxKind.ModuleBlock && n.kind !== SyntaxKind.ModuleDeclaration) return false;
1339
+ }
1340
+ return true;
1341
+ }
1342
+
1343
+ function isNonGenericObjectType(c: Checker, t: Type): boolean {
1344
+ return (t.flags & TypeFlags.Object) !== 0 && !isGenericMappedType(c, t);
1345
+ }
1346
+
1347
+ function hasMappedNameType(t: MappedType): boolean {
1348
+ return t.declaration !== undefined && (t.declaration as MappedTypeNode).nameType !== undefined;
1349
+ }
1350
+
1351
+ /** `(T | U)[K]` as `T[K] | U[K]` and `(T & U)[K]` as `T[K] & U[K]`. */
1352
+ function distributeIndexOverObjectType(c: Checker, objectType: Type, indexType: Type): Type | undefined {
1353
+ if (
1354
+ (objectType.flags & TypeFlags.Union) !== 0 ||
1355
+ ((objectType.flags & TypeFlags.Intersection) !== 0 && !shouldDeferIndexType(c, objectType, IndexFlags.None))
1356
+ ) {
1357
+ const types: Type[] = [];
1358
+ for (const t of typesOf(objectType)) types.push(getSimplifiedType(c, getIndexedAccessType(c, t, indexType), false));
1359
+ return (objectType.flags & TypeFlags.Intersection) !== 0 ? getIntersectionType(c, types) : getUnionType(c, types);
1360
+ }
1361
+ return undefined;
1362
+ }
1363
+
1364
+ /** An object with a property of type `any` for each string literal in `t`. */
1365
+ function createEmptyObjectTypeFromStringLiteral(c: Checker, t: Type): Type {
1366
+ const members = new Map<string, Symbol>();
1367
+ for (const u of distributedTypes(t)) {
1368
+ if ((u.flags & TypeFlags.StringLiteral) === 0) continue;
1369
+ const name = (u as LiteralType).stringValue;
1370
+ const literalProp = c.newSymbol(SymbolFlags.Property, name);
1371
+ c.symbolTypes.set(getSymbolId(literalProp), c.anyType);
1372
+ if (u.symbol !== undefined) {
1373
+ literalProp.declarations = u.symbol.declarations;
1374
+ literalProp.valueDeclaration = u.symbol.valueDeclaration;
1375
+ }
1376
+ members.set(name, literalProp);
1377
+ }
1378
+ const indexInfos: IndexInfo[] =
1379
+ (t.flags & TypeFlags.String) !== 0 ? [newIndexInfo(c.stringType, c.emptyObjectType, false, undefined)] : [];
1380
+ return createAnonymousType(c, undefined, members, [], [], indexInfos);
1381
+ }
1382
+
1383
+ export function isTypeParameterAtTopLevel(c: Checker, t: Type, tp: Type, depth: number): boolean {
1384
+ if (t === tp) return true;
1385
+ if ((t.flags & TypeFlags.UnionOrIntersection) !== 0) {
1386
+ for (const u of typesOf(t)) if (isTypeParameterAtTopLevel(c, u, tp, depth)) return true;
1387
+ return false;
1388
+ }
1389
+ return (
1390
+ depth < 3 &&
1391
+ (t.flags & TypeFlags.Conditional) !== 0 &&
1392
+ (isTypeParameterAtTopLevel(c, getTrueTypeFromConditionalType(c, t as ConditionalType), tp, depth + 1) ||
1393
+ isTypeParameterAtTopLevel(c, getFalseTypeFromConditionalType(c, t as ConditionalType), tp, depth + 1))
1394
+ );
1395
+ }
1396
+
1397
+ function isTypeParameterAtTopLevelInReturnType(c: Checker, signature: Signature, typeParameter: Type): boolean {
1398
+ const typePredicate = getTypePredicateOfSignature(c, signature);
1399
+ if (typePredicate !== undefined)
1400
+ return typePredicate.type !== undefined && isTypeParameterAtTopLevel(c, typePredicate.type, typeParameter, 0);
1401
+ return isTypeParameterAtTopLevel(c, getReturnTypeOfSignature(c, signature), typeParameter, 0);
1402
+ }
1403
+
1404
+ function isTypeOrBaseIdenticalTo(c: Checker, s: Type, t: Type): boolean {
1405
+ if (t === c.missingType) return s === t;
1406
+ return (
1407
+ isTypeIdenticalTo(c, s, t) ||
1408
+ ((t.flags & TypeFlags.String) !== 0 && (s.flags & TypeFlags.StringLiteral) !== 0) ||
1409
+ ((t.flags & TypeFlags.Number) !== 0 && (s.flags & TypeFlags.NumberLiteral) !== 0)
1410
+ );
1411
+ }
1412
+
1413
+ function isTypeCloselyMatchedBy(s: Type, t: Type): boolean {
1414
+ if (
1415
+ (s.flags & TypeFlags.Object) !== 0 &&
1416
+ (t.flags & TypeFlags.Object) !== 0 &&
1417
+ s.symbol !== undefined &&
1418
+ s.symbol === t.symbol
1419
+ )
1420
+ return true;
1421
+ const sa = s.alias;
1422
+ const ta = t.alias;
1423
+ return sa !== undefined && ta !== undefined && sa.typeArguments.length !== 0 && sa.symbol === ta.symbol;
1424
+ }
1425
+
1426
+ function typesDefinitelyUnrelated(c: Checker, source: Type, target: Type): boolean {
1427
+ // Tuples of incompatible arities, or objects that each have a property missing in the other.
1428
+ if (isTupleType(source) && isTupleType(target)) {
1429
+ const s = tupleTargetOf(source);
1430
+ const t = tupleTargetOf(target);
1431
+ return (
1432
+ ((t.combinedFlags & ElementFlags.Variadic) === 0 && t.minLength > s.minLength) ||
1433
+ ((t.combinedFlags & ElementFlags.Variable) === 0 &&
1434
+ ((s.combinedFlags & ElementFlags.Variable) !== 0 || t.fixedLength < s.fixedLength))
1435
+ );
1436
+ }
1437
+ return hasUnmatchedProperty(c, source, target, true) && hasUnmatchedProperty(c, target, source, false);
1438
+ }
1439
+
1440
+ /**
1441
+ * Whether `getUnmatchedProperty(c, source, target, false, matchDiscriminantProperties)` finds a
1442
+ * property, without creating every property of a union or intersection target whose properties
1443
+ * aren't resolved yet. That test reports only required properties: a union property is optional
1444
+ * when it is optional in any constituent, an intersection property when it is optional in every
1445
+ * constituent that has it. So only names required in a constituent (of those
1446
+ * `getPropertiesOfUnionOrIntersectionType` reads) are candidates, and the search stops at the first
1447
+ * unmatched one. A union property is created only when the result can depend on it: when the source
1448
+ * lacks the name, or for the discriminant test when the first constituent's property type is a unit
1449
+ * type or never (otherwise the union of the constituents' types is not a unit type).
1450
+ */
1451
+ function hasUnmatchedProperty(c: Checker, source: Type, target: Type, matchDiscriminantProperties: boolean): boolean {
1452
+ const t = getReducedApparentType(c, target);
1453
+ if (
1454
+ (t.flags & TypeFlags.UnionOrIntersection) === 0 ||
1455
+ sideOf(c, t as UnionOrIntersectionType).resolvedProperties !== undefined
1456
+ )
1457
+ return getUnmatchedProperty(c, source, target, false, matchDiscriminantProperties) !== undefined;
1458
+ const containingType = t as UnionOrIntersectionType;
1459
+ const isUnion = (t.flags & TypeFlags.Union) !== 0;
1460
+ const checked = new Set<string>();
1461
+ for (const current of containingType.types) {
1462
+ for (const prop of getPropertiesOfType(c, current)) {
1463
+ const name = prop.name;
1464
+ if ((prop.flags & SymbolFlags.Optional) !== 0) {
1465
+ if (isUnion) checked.add(name);
1466
+ continue;
1467
+ }
1468
+ if (checked.has(name)) continue;
1469
+ checked.add(name);
1470
+ if (
1471
+ isUnion &&
1472
+ getPropertyOfType(c, source, name) !== undefined &&
1473
+ (!matchDiscriminantProperties || (getTypeOfSymbol(c, prop).flags & (TypeFlags.Unit | TypeFlags.Never)) === 0)
1474
+ )
1475
+ continue;
1476
+ const combined = getPropertyOfUnionOrIntersectionType(c, containingType, name, !isUnion);
1477
+ if (combined !== undefined && isUnmatchedProperty(c, source, combined, false, matchDiscriminantProperties))
1478
+ return true;
1479
+ }
1480
+ if (isUnion && getIndexInfosOfType(c, current).length === 0) break;
1481
+ }
1482
+ return false;
1483
+ }
1484
+
1485
+ function isTupleTypeStructureMatching(t1: Type, t2: Type): boolean {
1486
+ if (getTypeReferenceArity(t1) !== getTypeReferenceArity(t2)) return false;
1487
+ const infos1 = tupleTargetOf(t1).elementInfos;
1488
+ const infos2 = tupleTargetOf(t2).elementInfos;
1489
+ for (let i = 0; i < infos1.length; i++)
1490
+ if ((infos1[i]!.flags & ElementFlags.Variable) !== (infos2[i]!.flags & ElementFlags.Variable)) return false;
1491
+ return true;
1492
+ }
1493
+
1494
+ export function isConstTypeVariable(c: Checker, t: Type | undefined, depth: number): boolean {
1495
+ if (depth >= 5 || t === undefined) return false;
1496
+ if ((t.flags & TypeFlags.TypeParameter) !== 0) {
1497
+ if (t.symbol === undefined) return false;
1498
+ for (const d of t.symbol.declarations) if (hasSyntacticModifier(d, ModifierFlags.Const)) return true;
1499
+ return false;
1500
+ }
1501
+ if ((t.flags & TypeFlags.UnionOrIntersection) !== 0) {
1502
+ for (const s of typesOf(t)) if (isConstTypeVariable(c, s, depth)) return true;
1503
+ return false;
1504
+ }
1505
+ if ((t.flags & TypeFlags.IndexedAccess) !== 0)
1506
+ return isConstTypeVariable(c, (t as IndexedAccessType).objectType, depth + 1);
1507
+ if ((t.flags & TypeFlags.Conditional) !== 0)
1508
+ return isConstTypeVariable(c, getConstraintOfConditionalType(c, t), depth + 1);
1509
+ if ((t.flags & TypeFlags.Substitution) !== 0) return isConstTypeVariable(c, (t as SubstitutionType).baseType, depth);
1510
+ if ((t.objectFlags & ObjectFlags.Mapped) !== 0) {
1511
+ const typeVariable = getHomomorphicTypeVariable(c, t as MappedType);
1512
+ return typeVariable !== undefined && isConstTypeVariable(c, typeVariable, depth);
1513
+ }
1514
+ if (isGenericTupleType(t)) {
1515
+ const elements = getElementTypes(c, t);
1516
+ const infos = tupleTargetOf(t).elementInfos;
1517
+ for (let i = 0; i < elements.length; i++)
1518
+ if ((infos[i]!.flags & ElementFlags.Variadic) !== 0 && isConstTypeVariable(c, elements[i]!, depth)) return true;
1519
+ }
1520
+ return false;
1521
+ }
1522
+
1523
+ export function isMutableArrayLikeType(c: Checker, t: Type): boolean {
1524
+ return (
1525
+ isMutableArrayOrTuple(c, t) ||
1526
+ ((t.flags & (TypeFlags.Any | TypeFlags.Nullable)) === 0 && isTypeAssignableTo(c, t, c.anyArrayType))
1527
+ );
1528
+ }
1529
+
1530
+ function typePredicateKindsMatch(a: TypePredicate, b: TypePredicate): boolean {
1531
+ return a.kind === b.kind && a.parameterIndex === b.parameterIndex;
1532
+ }
1533
+
1534
+ /** Calls `callback` with each pair of corresponding parameter types of `source` and `target`. */
1535
+ export function applyToParameterTypes(
1536
+ c: Checker,
1537
+ source: Signature,
1538
+ target: Signature,
1539
+ callback: (s: Type, t: Type) => void,
1540
+ ): void {
1541
+ const sourceCount = getParameterCount(c, source);
1542
+ const targetCount = getParameterCount(c, target);
1543
+ const sourceRestType = getEffectiveRestType(c, source);
1544
+ const targetRestType = getEffectiveRestType(c, target);
1545
+ const targetNonRestCount = targetRestType !== undefined ? targetCount - 1 : targetCount;
1546
+ const paramCount = sourceRestType !== undefined ? targetNonRestCount : Math.min(sourceCount, targetNonRestCount);
1547
+ const sourceThisType = getThisTypeOfSignature(c, source);
1548
+ if (sourceThisType !== undefined) {
1549
+ const targetThisType = getThisTypeOfSignature(c, target);
1550
+ if (targetThisType !== undefined) callback(sourceThisType, targetThisType);
1551
+ }
1552
+ for (let i = 0; i < paramCount; i++) callback(getTypeAtPosition(c, source, i), getTypeAtPosition(c, target, i));
1553
+ if (targetRestType !== undefined)
1554
+ callback(
1555
+ getRestTypeAtPosition(
1556
+ c,
1557
+ source,
1558
+ paramCount,
1559
+ isConstTypeVariable(c, targetRestType, 0) && !someType(targetRestType, (t) => isMutableArrayLikeType(c, t)),
1560
+ ),
1561
+ targetRestType,
1562
+ );
1563
+ }
1564
+
1565
+ export function applyToReturnTypes(
1566
+ c: Checker,
1567
+ source: Signature,
1568
+ target: Signature,
1569
+ callback: (s: Type, t: Type) => void,
1570
+ ): void {
1571
+ const targetTypePredicate = getTypePredicateOfSignature(c, target);
1572
+ if (targetTypePredicate !== undefined) {
1573
+ const sourceTypePredicate = getTypePredicateOfSignature(c, source);
1574
+ if (
1575
+ sourceTypePredicate !== undefined &&
1576
+ typePredicateKindsMatch(sourceTypePredicate, targetTypePredicate) &&
1577
+ sourceTypePredicate.type !== undefined &&
1578
+ targetTypePredicate.type !== undefined
1579
+ ) {
1580
+ callback(sourceTypePredicate.type, targetTypePredicate.type);
1581
+ return;
1582
+ }
1583
+ }
1584
+ const targetReturnType = getReturnTypeOfSignature(c, target);
1585
+ if (couldContainTypeVariables(c, targetReturnType)) callback(getReturnTypeOfSignature(c, source), targetReturnType);
1586
+ }
1587
+
1588
+ /** `signature` with its type parameters replaced by their base constraints. */
1589
+ export function getBaseSignature(c: Checker, signature: Signature): Signature {
1590
+ const typeParameters = signature.typeParameters;
1591
+ if (typeParameters.length === 0) return signature;
1592
+ const side = signatureSideOf(c, signature);
1593
+ if (side.baseSignatureCache !== undefined) return side.baseSignatureCache;
1594
+ const constraints: Type[] = [];
1595
+ for (const tp of typeParameters) constraints.push(getConstraintOfTypeParameter(c, tp) ?? c.unknownType);
1596
+ const baseConstraintMapper = newTypeMapper(typeParameters, constraints);
1597
+ let baseConstraints: Type[] = [];
1598
+ for (const tp of typeParameters) baseConstraints.push(instantiateType(c, tp, baseConstraintMapper));
1599
+ // Resolve non-circular interdependent constraints, then erase what remains circular.
1600
+ for (let i = 0; i < typeParameters.length - 1; i++)
1601
+ baseConstraints = instantiateTypes(c, baseConstraints, baseConstraintMapper);
1602
+ baseConstraints = instantiateTypes(c, baseConstraints, new ArrayToSingleTypeMapper(typeParameters, c.anyType));
1603
+ const result = instantiateSignatureEx(c, signature, newTypeMapper(typeParameters, baseConstraints), true);
1604
+ side.baseSignatureCache = result;
1605
+ return result;
1606
+ }
1607
+
1608
+ export function getTypeParametersForMapper(c: Checker, signature: Signature): Type[] {
1609
+ const result: Type[] = [];
1610
+ for (const tp of signature.typeParameters) result.push(instantiateType(c, tp, (tp as TypeParameter).mapper));
1611
+ return result;
1612
+ }
1613
+
1614
+ /** The generic `signature` instantiated in the context of the non-generic `contextualSignature`. */
1615
+ export function instantiateSignatureInContextOf(
1616
+ c: Checker,
1617
+ signature: Signature,
1618
+ contextualSignature: Signature,
1619
+ inferenceContext: InferenceContext | undefined,
1620
+ compareTypes: TypeComparer | undefined,
1621
+ ): Signature {
1622
+ const context = createInferenceContext(
1623
+ c,
1624
+ getTypeParametersForMapper(c, signature),
1625
+ signature,
1626
+ InferenceFlags.None,
1627
+ compareTypes,
1628
+ );
1629
+ // Clone so that inferring through a rest type parameter doesn't fix it.
1630
+ const restType = getEffectiveRestType(c, contextualSignature);
1631
+ const mapper =
1632
+ inferenceContext !== undefined
1633
+ ? restType !== undefined && (restType.flags & TypeFlags.TypeParameter) !== 0
1634
+ ? inferenceContext.nonFixingMapper
1635
+ : inferenceContext.mapper
1636
+ : undefined;
1637
+ const sourceSignature =
1638
+ mapper !== undefined ? instantiateSignature(c, contextualSignature, mapper) : contextualSignature;
1639
+ applyToParameterTypes(c, sourceSignature, signature, (source, target) =>
1640
+ inferTypes(c, context.inferences, source, target, InferencePriority.None, false),
1641
+ );
1642
+ if (inferenceContext === undefined)
1643
+ applyToReturnTypes(c, contextualSignature, signature, (source, target) =>
1644
+ inferTypes(c, context.inferences, source, target, InferencePriority.ReturnType, false),
1645
+ );
1646
+ return getSignatureInstantiation(
1647
+ c,
1648
+ signature,
1649
+ getInferredTypes(c, context),
1650
+ contextualSignature.declaration !== undefined &&
1651
+ (contextualSignature.declaration.flags & NodeFlags.JavaScriptFile) !== 0,
1652
+ );
1653
+ }
1654
+
1655
+ // ---- Template literal inference
1656
+
1657
+ /**
1658
+ * Whether `source`, a string literal or a template literal type, fails the start and end text test of
1659
+ * `inferFromLiteralPartsToTemplateLiteral` against `target`: its first text does not start with the
1660
+ * target's first text, its last text does not end with the target's last text, or a string literal
1661
+ * is shorter than both. `inferTypesFromTemplateLiteralType` returns undefined then.
1662
+ */
1663
+ export function failsTemplateLiteralTextTest(source: Type, target: TemplateLiteralType): boolean {
1664
+ const targetTexts = target.texts;
1665
+ const targetStartText = targetTexts[0]!;
1666
+ const targetEndText = targetTexts[targetTexts.length - 1]!;
1667
+ if ((source.flags & TypeFlags.StringLiteral) !== 0) {
1668
+ const text = (source as LiteralType).stringValue;
1669
+ return (
1670
+ text.length < targetStartText.length + targetEndText.length ||
1671
+ !text.startsWith(targetStartText) ||
1672
+ !text.endsWith(targetEndText)
1673
+ );
1674
+ }
1675
+ const sourceTexts = (source as TemplateLiteralType).texts;
1676
+ return !sourceTexts[0]!.startsWith(targetStartText) || !sourceTexts[sourceTexts.length - 1]!.endsWith(targetEndText);
1677
+ }
1678
+
1679
+ /**
1680
+ * Whether `source` is a string literal, or a template literal type whose placeholders are `string`,
1681
+ * `number` or `bigint`, that fails the start and end text test against `target`. It is then not
1682
+ * assignable to `target`, and relating the two has no other effect: such a template has no type
1683
+ * variables for a variance marker mapper to find.
1684
+ */
1685
+ export function isUnmatchedTemplateLiteralKey(source: Type, target: TemplateLiteralType): boolean {
1686
+ if ((source.flags & TypeFlags.TemplateLiteral) !== 0) {
1687
+ for (const t of (source as TemplateLiteralType).types)
1688
+ if ((t.flags & (TypeFlags.String | TypeFlags.Number | TypeFlags.BigInt)) === 0) return false;
1689
+ } else if ((source.flags & TypeFlags.StringLiteral) === 0) return false;
1690
+ return failsTemplateLiteralTextTest(source, target);
1691
+ }
1692
+
1693
+ /** The types matched by `target`'s placeholders in `source`, or undefined if it doesn't match. */
1694
+ export function inferTypesFromTemplateLiteralType(
1695
+ c: Checker,
1696
+ source: Type,
1697
+ target: TemplateLiteralType,
1698
+ ): Type[] | undefined {
1699
+ if ((source.flags & TypeFlags.StringLiteral) !== 0) {
1700
+ // Most string literals fail the start and end text test; apply it before building the
1701
+ // one-element source texts.
1702
+ if (failsTemplateLiteralTextTest(source, target)) return undefined;
1703
+ return inferFromLiteralPartsToTemplateLiteral(c, [(source as LiteralType).stringValue], emptyTypes, target);
1704
+ }
1705
+ if ((source.flags & TypeFlags.TemplateLiteral) !== 0) {
1706
+ const s = source as TemplateLiteralType;
1707
+ if (arraysEqual(s.texts, target.texts)) {
1708
+ const result: Type[] = [];
1709
+ for (let i = 0; i < s.types.length; i++) {
1710
+ const t = s.types[i]!;
1711
+ result.push(
1712
+ isTypeAssignableTo(c, getBaseConstraintOrType(c, t), getBaseConstraintOrType(c, target.types[i]!))
1713
+ ? t
1714
+ : getStringLikeTypeForType(c, t),
1715
+ );
1716
+ }
1717
+ return result;
1718
+ }
1719
+ return inferFromLiteralPartsToTemplateLiteral(c, s.texts, s.types, target);
1720
+ }
1721
+ return undefined;
1722
+ }
1723
+
1724
+ function arraysEqual(a: string[], b: string[]): boolean {
1725
+ if (a.length !== b.length) return false;
1726
+ for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
1727
+ return true;
1728
+ }
1729
+
1730
+ function getStringLikeTypeForType(c: Checker, t: Type): Type {
1731
+ return (t.flags & (TypeFlags.Any | TypeFlags.StringLike)) !== 0 ? t : getTemplateLiteralType(c, ['', ''], [t]);
1732
+ }
1733
+
1734
+ /** Matches the text and type parts of a source literal against a target template literal. */
1735
+ class TemplateMatcher {
1736
+ readonly c: Checker;
1737
+ readonly sourceTexts: string[];
1738
+ readonly sourceTypes: Type[];
1739
+ readonly lastSourceIndex: number;
1740
+ readonly remainingEndText: string;
1741
+ seg = 0;
1742
+ pos: number;
1743
+ readonly matches: Type[] = [];
1744
+
1745
+ constructor(c: Checker, sourceTexts: string[], sourceTypes: Type[], remainingEndText: string, pos: number) {
1746
+ this.c = c;
1747
+ this.sourceTexts = sourceTexts;
1748
+ this.sourceTypes = sourceTypes;
1749
+ this.lastSourceIndex = sourceTexts.length - 1;
1750
+ this.remainingEndText = remainingEndText;
1751
+ this.pos = pos;
1752
+ }
1753
+
1754
+ sourceText(index: number): string {
1755
+ return index < this.lastSourceIndex ? this.sourceTexts[index]! : this.remainingEndText;
1756
+ }
1757
+
1758
+ addMatch(s: number, p: number): void {
1759
+ let matchType: Type;
1760
+ if (s === this.seg) matchType = getStringLiteralType(this.c, this.sourceText(s).substring(this.pos, p));
1761
+ else {
1762
+ const texts: string[] = [this.sourceTexts[this.seg]!.substring(this.pos)];
1763
+ for (let i = this.seg + 1; i < s; i++) texts.push(this.sourceTexts[i]!);
1764
+ texts.push(this.sourceText(s).substring(0, p));
1765
+ matchType = getTemplateLiteralType(this.c, texts, this.sourceTypes.slice(this.seg, s));
1766
+ }
1767
+ this.matches.push(matchType);
1768
+ this.seg = s;
1769
+ this.pos = p;
1770
+ }
1771
+ }
1772
+
1773
+ function inferFromLiteralPartsToTemplateLiteral(
1774
+ c: Checker,
1775
+ sourceTexts: string[],
1776
+ sourceTypes: Type[],
1777
+ target: TemplateLiteralType,
1778
+ ): Type[] | undefined {
1779
+ const lastSourceIndex = sourceTexts.length - 1;
1780
+ const sourceStartText = sourceTexts[0]!;
1781
+ const sourceEndText = sourceTexts[lastSourceIndex]!;
1782
+ const targetTexts = target.texts;
1783
+ const lastTargetIndex = targetTexts.length - 1;
1784
+ const targetStartText = targetTexts[0]!;
1785
+ const targetEndText = targetTexts[lastTargetIndex]!;
1786
+ if (
1787
+ (lastSourceIndex === 0 && sourceStartText.length < targetStartText.length + targetEndText.length) ||
1788
+ !sourceStartText.startsWith(targetStartText) ||
1789
+ !sourceEndText.endsWith(targetEndText)
1790
+ )
1791
+ return undefined;
1792
+ const m = new TemplateMatcher(
1793
+ c,
1794
+ sourceTexts,
1795
+ sourceTypes,
1796
+ sourceEndText.substring(0, sourceEndText.length - targetEndText.length),
1797
+ targetStartText.length,
1798
+ );
1799
+ for (let i = 1; i < lastTargetIndex; i++) {
1800
+ const delim = targetTexts[i]!;
1801
+ if (delim.length > 0) {
1802
+ let s = m.seg;
1803
+ let p = m.pos;
1804
+ for (;;) {
1805
+ const d = m.sourceText(s).indexOf(delim, p);
1806
+ if (d >= 0) {
1807
+ p = d;
1808
+ break;
1809
+ }
1810
+ s++;
1811
+ if (s === sourceTexts.length) return undefined;
1812
+ p = 0;
1813
+ }
1814
+ m.addMatch(s, p);
1815
+ m.pos += delim.length;
1816
+ } else if (m.pos < m.sourceText(m.seg).length) {
1817
+ // Consume one code point.
1818
+ const code = m.sourceText(m.seg).codePointAt(m.pos)!;
1819
+ m.addMatch(m.seg, m.pos + (code > 0xffff ? 2 : 1));
1820
+ } else if (m.seg < lastSourceIndex) m.addMatch(m.seg + 1, 0);
1821
+ else return undefined;
1822
+ }
1823
+ m.addMatch(lastSourceIndex, m.sourceText(lastSourceIndex).length);
1824
+ return m.matches;
1825
+ }
1826
+
1827
+ /** For a string literal inferred to a placeholder constrained to primitives, the literal type the constraint prefers. */
1828
+ function getTemplatePlaceholderInference(c: Checker, source: LiteralType, constraint: Type): Type | undefined {
1829
+ let allTypeFlags = TypeFlags.None;
1830
+ for (const t of distributedTypes(constraint)) allTypeFlags |= t.flags;
1831
+ // A constraint including `string` needs no more specific type.
1832
+ if ((allTypeFlags & TypeFlags.String) !== 0) return undefined;
1833
+ const str = source.stringValue;
1834
+ if ((allTypeFlags & TypeFlags.NumberLike) !== 0 && !isValidNumberString(str, true))
1835
+ allTypeFlags &= ~TypeFlags.NumberLike;
1836
+ if ((allTypeFlags & TypeFlags.BigIntLike) !== 0 && !isValidBigIntString(str, true))
1837
+ allTypeFlags &= ~TypeFlags.BigIntLike;
1838
+ let matching: Type = c.neverType;
1839
+ for (const t of distributedTypes(constraint))
1840
+ matching = choosePlaceholderType(c, matching, t, source, str, allTypeFlags);
1841
+ return (matching.flags & TypeFlags.Never) === 0 ? matching : undefined;
1842
+ }
1843
+
1844
+ function choosePlaceholderType(
1845
+ c: Checker,
1846
+ left: Type,
1847
+ right: Type,
1848
+ source: LiteralType,
1849
+ str: string,
1850
+ allTypeFlags: TypeFlags,
1851
+ ): Type {
1852
+ if ((right.flags & allTypeFlags) === 0) return left;
1853
+ if ((left.flags & TypeFlags.String) !== 0) return left;
1854
+ if ((right.flags & TypeFlags.String) !== 0) return source;
1855
+ if ((left.flags & TypeFlags.TemplateLiteral) !== 0) return left;
1856
+ if (
1857
+ (right.flags & TypeFlags.TemplateLiteral) !== 0 &&
1858
+ isTypeMatchedByTemplateLiteralType(c, source, right as TemplateLiteralType)
1859
+ )
1860
+ return source;
1861
+ if ((left.flags & TypeFlags.StringMapping) !== 0) return left;
1862
+ if ((right.flags & TypeFlags.StringMapping) !== 0 && str === applyStringMapping(right.symbol!, str)) return source;
1863
+ if ((left.flags & TypeFlags.StringLiteral) !== 0) return left;
1864
+ if ((right.flags & TypeFlags.StringLiteral) !== 0 && (right as LiteralType).stringValue === str) return right;
1865
+ if ((left.flags & TypeFlags.Number) !== 0) return left;
1866
+ if ((right.flags & TypeFlags.Number) !== 0) return getNumberLiteralType(c, Number(str));
1867
+ if ((left.flags & TypeFlags.Enum) !== 0) return left;
1868
+ if ((right.flags & TypeFlags.Enum) !== 0) return getNumberLiteralType(c, Number(str));
1869
+ if ((left.flags & TypeFlags.NumberLiteral) !== 0) return left;
1870
+ if ((right.flags & TypeFlags.NumberLiteral) !== 0 && (right as LiteralType).numberValue === Number(str)) return right;
1871
+ if ((left.flags & TypeFlags.BigInt) !== 0) return left;
1872
+ if ((right.flags & TypeFlags.BigInt) !== 0) return getBigIntLiteralType(c, parsePseudoBigInt(str));
1873
+ if ((left.flags & TypeFlags.BigIntLiteral) !== 0) return left;
1874
+ if ((right.flags & TypeFlags.BigIntLiteral) !== 0 && (right as LiteralType).stringValue === str) return right;
1875
+ if ((left.flags & TypeFlags.Boolean) !== 0) return left;
1876
+ if ((right.flags & TypeFlags.Boolean) !== 0)
1877
+ return str === 'true' ? c.trueType : str === 'false' ? c.falseType : c.booleanType;
1878
+ if ((left.flags & TypeFlags.BooleanLiteral) !== 0) return left;
1879
+ if ((right.flags & TypeFlags.BooleanLiteral) !== 0 && (right as LiteralType).stringValue === str) return right;
1880
+ if ((left.flags & TypeFlags.Undefined) !== 0) return left;
1881
+ if ((right.flags & TypeFlags.Undefined) !== 0 && (right as IntrinsicType).intrinsicName === str) return right;
1882
+ if ((left.flags & TypeFlags.Null) !== 0) return left;
1883
+ if ((right.flags & TypeFlags.Null) !== 0 && (right as IntrinsicType).intrinsicName === str) return right;
1884
+ return left;
1885
+ }
1886
+
1887
+ export function isValidNumberString(s: string, roundTripOnly: boolean): boolean {
1888
+ if (s === '') return false;
1889
+ const n = Number(s);
1890
+ return isFinite(n) && (!roundTripOnly || String(n) === s);
1891
+ }
1892
+
1893
+ /** Whether `s` scans as a bigint literal without separators; round-trippable ones print as written. */
1894
+ export function isValidBigIntString(s: string, roundTripOnly: boolean): boolean {
1895
+ if (roundTripOnly) return /^-?(0|[1-9][0-9]*)$/.test(s) && s !== '-0';
1896
+ return /^-?(0|[1-9][0-9]*|0[xX][0-9a-fA-F]+|0[bB][01]+|0[oO][0-7]+)$/.test(s);
1897
+ }
1898
+
1899
+ // ---- Reverse mapped types
1900
+
1901
+ /** Infers a source type for the homomorphic mapped type `{ [P in keyof T]: X }`, cached. */
1902
+ export function inferTypeForHomomorphicMappedType(
1903
+ c: Checker,
1904
+ source: Type,
1905
+ target: MappedType,
1906
+ constraint: IndexType,
1907
+ ): Type | undefined {
1908
+ const key = source.id + ',' + target.id + ',' + constraint.id;
1909
+ const caches = c.inferenceCaches;
1910
+ if (caches.reverseHomomorphicMapped.has(key)) return caches.reverseHomomorphicMapped.get(key);
1911
+ const t = createReverseMappedType(c, source, target, constraint);
1912
+ caches.reverseHomomorphicMapped.set(key, t);
1913
+ return t;
1914
+ }
1915
+
1916
+ function createReverseMappedType(
1917
+ c: Checker,
1918
+ source: Type,
1919
+ target: MappedType,
1920
+ constraint: IndexType,
1921
+ ): Type | undefined {
1922
+ // Reverse mappable: a string index signature, or properties of a partially inferable type.
1923
+ if (
1924
+ !(
1925
+ getIndexInfoOfType(c, source, c.stringType) !== undefined ||
1926
+ (getPropertiesOfType(c, source).length !== 0 && isPartiallyInferableType(c, source))
1927
+ )
1928
+ )
1929
+ return undefined;
1930
+ // Arrays and tuples map to arrays and tuples of reverse-mapped elements.
1931
+ if (isArrayType(c, source)) {
1932
+ const elementType = inferReverseMappedType(c, getTypeArguments(c, source)[0]!, target, constraint);
1933
+ if (elementType === undefined) return undefined;
1934
+ return createArrayTypeEx(c, elementType, isReadonlyArrayType(c, source));
1935
+ }
1936
+ if (isTupleType(source)) {
1937
+ const elementTypes: Type[] = [];
1938
+ for (const t of getElementTypes(c, source)) {
1939
+ const e = inferReverseMappedType(c, t, target, constraint);
1940
+ if (e === undefined) return undefined;
1941
+ elementTypes.push(e);
1942
+ }
1943
+ let elementInfos = tupleTargetOf(source).elementInfos;
1944
+ if ((getMappedTypeModifiers(target) & MappedTypeModifiers.IncludeOptional) !== 0)
1945
+ elementInfos = elementInfos.map((info) =>
1946
+ (info.flags & ElementFlags.Optional) !== 0
1947
+ ? new TupleElementInfo(ElementFlags.Required, info.labeledDeclaration)
1948
+ : info,
1949
+ );
1950
+ return createTupleTypeEx(c, elementTypes, elementInfos, tupleTargetOf(source).readonly);
1951
+ }
1952
+ // Other object types map to an object whose properties are reverse-mapped lazily.
1953
+ const reversed = newObjectType(c, ObjectFlags.ReverseMapped | ObjectFlags.Anonymous, undefined) as ReverseMappedType;
1954
+ reversed.source = source;
1955
+ reversed.mappedType = target;
1956
+ reversed.constraintType = constraint;
1957
+ return reversed;
1958
+ }
1959
+
1960
+ /** Not marked non-inferable, or an object literal or tuple with some inferable part. */
1961
+ function isPartiallyInferableType(c: Checker, t: Type): boolean {
1962
+ if ((t.objectFlags & ObjectFlags.NonInferrableType) === 0) return true;
1963
+ if (isObjectLiteralType(t))
1964
+ for (const p of getPropertiesOfType(c, t)) if (isPartiallyInferableType(c, getTypeOfSymbol(c, p))) return true;
1965
+ if (isTupleType(t)) for (const e of getElementTypes(c, t)) if (isPartiallyInferableType(c, e)) return true;
1966
+ return false;
1967
+ }
1968
+
1969
+ export function inferReverseMappedType(
1970
+ c: Checker,
1971
+ source: Type,
1972
+ target: MappedType,
1973
+ constraint: IndexType,
1974
+ ): Type | undefined {
1975
+ const key = source.id + ',' + target.id + ',' + constraint.id;
1976
+ const caches = c.inferenceCaches;
1977
+ if (caches.reverseMapped.has(key)) return caches.reverseMapped.get(key) ?? c.unknownType;
1978
+ const stackDepth = caches.reverseStackDepth;
1979
+ setStackEntry(caches.reverseSourceStack, stackDepth, source);
1980
+ setStackEntry(caches.reverseTargetStack, stackDepth, target as Type);
1981
+ caches.reverseStackDepth = stackDepth + 1;
1982
+ const saveExpandingFlags = caches.reverseExpandingFlags;
1983
+ if (isDeeplyNestedType(c, source, caches.reverseSourceStack, stackDepth + 1, 2))
1984
+ caches.reverseExpandingFlags |= ExpandingFlags.Source;
1985
+ if (isDeeplyNestedType(c, target, caches.reverseTargetStack, stackDepth + 1, 2))
1986
+ caches.reverseExpandingFlags |= ExpandingFlags.Target;
1987
+ let t: Type | undefined = undefined;
1988
+ if (caches.reverseExpandingFlags !== ExpandingFlags.Both) {
1989
+ const typeParameter = getIndexedAccessType(c, constraint.target, getTypeParameterFromMappedType(c, target));
1990
+ const templateType = getTemplateTypeFromMappedType(c, target);
1991
+ const inference = new InferenceInfo(typeParameter);
1992
+ inferTypes(c, [inference], source, templateType, InferencePriority.None, false);
1993
+ t = getWidenedType(c, getTypeFromInference(c, inference) ?? c.unknownType);
1994
+ }
1995
+ caches.reverseStackDepth = stackDepth;
1996
+ caches.reverseExpandingFlags = saveExpandingFlags;
1997
+ caches.reverseMapped.set(key, t);
1998
+ return t;
1999
+ }
2000
+
2001
+ export function resolveReverseMappedTypeMembers(c: Checker, t: ReverseMappedType): void {
2002
+ const source = t.source!;
2003
+ const mappedType = t.mappedType as MappedType;
2004
+ const constraintType = t.constraintType as IndexType;
2005
+ const indexInfo = getIndexInfoOfType(c, source, c.stringType);
2006
+ const modifiers = getMappedTypeModifiers(mappedType);
2007
+ const readonlyMask = (modifiers & MappedTypeModifiers.IncludeReadonly) === 0;
2008
+ const optionalMask = (modifiers & MappedTypeModifiers.IncludeOptional) !== 0 ? 0 : SymbolFlags.Optional;
2009
+ const indexInfos: IndexInfo[] =
2010
+ indexInfo !== undefined
2011
+ ? [
2012
+ newIndexInfo(
2013
+ c.stringType,
2014
+ inferReverseMappedType(c, indexInfo.valueType, mappedType, constraintType) ?? c.unknownType,
2015
+ readonlyMask && indexInfo.isReadonly,
2016
+ undefined,
2017
+ ),
2018
+ ]
2019
+ : [];
2020
+ const members = new Map<string, Symbol>();
2021
+ const limitedConstraint = getLimitedConstraint(c, t);
2022
+ for (const prop of getPropertiesOfType(c, source)) {
2023
+ // With an intersection constraint, skip properties the filtering literals exclude.
2024
+ if (limitedConstraint !== undefined) {
2025
+ const propertyNameType = getLiteralTypeFromProperty(c, prop, TypeFlags.StringOrNumberLiteralOrUnique, false);
2026
+ if (!isTypeAssignableTo(c, propertyNameType, limitedConstraint)) continue;
2027
+ }
2028
+ const checkFlags = CheckFlags.ReverseMapped | (readonlyMask && isReadonlySymbol(c, prop) ? CheckFlags.Readonly : 0);
2029
+ const inferredProp = c.newSymbolWithCheckFlags(
2030
+ SymbolFlags.Property | (prop.flags & optionalMask),
2031
+ prop.name,
2032
+ checkFlags,
2033
+ );
2034
+ inferredProp.declarations = prop.declarations;
2035
+ const links = c.symbolLinks(inferredProp);
2036
+ const id = inferredProp.id;
2037
+ c.symbolNameTypes.set(id, c.symbolNameTypes.get(getSymbolId(prop)));
2038
+ links.reverseMappedPropertyType = getTypeOfSymbol(c, prop);
2039
+ const constraintTarget = constraintType.target;
2040
+ if (
2041
+ (constraintTarget.flags & TypeFlags.IndexedAccess) !== 0 &&
2042
+ ((constraintTarget as IndexedAccessType).objectType.flags & TypeFlags.TypeParameter) !== 0 &&
2043
+ ((constraintTarget as IndexedAccessType).indexType.flags & TypeFlags.TypeParameter) !== 0
2044
+ ) {
2045
+ // `{[K in keyof T[K_1]]: T[K_1]}` reverse-maps like `{[K in keyof T]: T}`.
2046
+ const newTypeParam = (constraintTarget as IndexedAccessType).objectType;
2047
+ links.reverseMappedMappedType = replaceIndexedAccess(
2048
+ c,
2049
+ mappedType,
2050
+ constraintTarget as IndexedAccessType,
2051
+ newTypeParam,
2052
+ );
2053
+ links.reverseMappedConstraintType = getIndexType(c, newTypeParam);
2054
+ } else {
2055
+ links.reverseMappedMappedType = mappedType;
2056
+ links.reverseMappedConstraintType = constraintType;
2057
+ }
2058
+ members.set(prop.name, inferredProp);
2059
+ }
2060
+ setStructuredTypeMembers(c, t, members, [], [], indexInfos);
2061
+ }
2062
+
2063
+ export function getTypeOfReverseMappedSymbol(c: Checker, symbol: Symbol): Type {
2064
+ const links = c.symbolLinks(symbol);
2065
+ const id = symbol.id;
2066
+ let type = c.symbolTypes.get(id);
2067
+ if (type === undefined) {
2068
+ type =
2069
+ inferReverseMappedType(
2070
+ c,
2071
+ links.reverseMappedPropertyType!,
2072
+ links.reverseMappedMappedType as MappedType,
2073
+ links.reverseMappedConstraintType as IndexType,
2074
+ ) ?? c.unknownType;
2075
+ c.symbolTypes.set(id, type);
2076
+ }
2077
+ return type;
2078
+ }
2079
+
2080
+ /** The filtering literals of an intersection constraint, e.g. `"a" | "b"` in `keyof U & ("a" | "b")`. */
2081
+ function getLimitedConstraint(c: Checker, t: ReverseMappedType): Type | undefined {
2082
+ const constraint = getConstraintTypeFromMappedType(c, t.mappedType as MappedType);
2083
+ if ((constraint.flags & TypeFlags.UnionOrIntersection) === 0) return undefined;
2084
+ const origin = (constraint.flags & TypeFlags.Union) !== 0 ? (constraint as UnionType).origin : constraint;
2085
+ if (origin === undefined || (origin.flags & TypeFlags.Intersection) === 0) return undefined;
2086
+ const limited = getIntersectionType(
2087
+ c,
2088
+ typesOf(origin).filter((u) => u !== t.constraintType),
2089
+ );
2090
+ return limited !== c.neverType ? limited : undefined;
2091
+ }
2092
+
2093
+ function replaceIndexedAccess(c: Checker, instantiable: Type, t: IndexedAccessType, replacement: Type): Type {
2094
+ // Map the index to 0 and the object to `[replacement]`, making the access `replacement`.
2095
+ return instantiateType(
2096
+ c,
2097
+ instantiable,
2098
+ newTypeMapper([t.indexType, t.objectType], [getNumberLiteralType(c, 0), createTupleType(c, [replacement])]),
2099
+ );
2100
+ }
2101
+
2102
+ export function instantiateReverseMappedType(c: Checker, t: ReverseMappedType, mapper: TypeMapper): Type {
2103
+ const innerMappedType = instantiateType(c, t.mappedType!, mapper);
2104
+ if ((innerMappedType.objectFlags & ObjectFlags.Mapped) === 0) return t;
2105
+ const innerIndexType = instantiateType(c, t.constraintType!, mapper);
2106
+ if ((innerIndexType.flags & TypeFlags.Index) === 0) return t;
2107
+ const inferred = inferTypeForHomomorphicMappedType(
2108
+ c,
2109
+ instantiateType(c, t.source!, mapper),
2110
+ innerMappedType as MappedType,
2111
+ innerIndexType as IndexType,
2112
+ );
2113
+ return inferred === undefined ? t : (inferred as Type);
2114
+ }
2115
+
2116
+ // ---- Inferred types
2117
+
2118
+ /** Infers early from intra-expression sites (context-sensitive elements of object and array literals). */
2119
+ export function inferFromIntraExpressionSites(c: Checker, context: InferenceContext): void {
2120
+ const sites = context.intraExpressionInferenceSites;
2121
+ context.intraExpressionInferenceSites = [];
2122
+ for (const site of sites) {
2123
+ const contextualType = getContextualTypeForInference(c, site.node);
2124
+ if (contextualType !== undefined)
2125
+ inferTypes(c, context.inferences, site.type, contextualType, InferencePriority.None, false);
2126
+ }
2127
+ }
2128
+
2129
+ export function getInferredType(c: Checker, context: InferenceContext, index: number): Type {
2130
+ const inference = context.inferences[index]!;
2131
+ if (inference.inferredType !== undefined) return inference.inferredType;
2132
+ if (inference.typeParameter === c.errorType) return inference.typeParameter;
2133
+ let inferredType: Type | undefined = undefined;
2134
+ let fallbackType: Type | undefined = undefined;
2135
+ const signature = context.signature;
2136
+ if (signature !== undefined) {
2137
+ const covariant = inference.candidates.length !== 0 ? getCovariantInference(c, inference, signature) : undefined;
2138
+ const contravariant = inference.contraCandidates.length !== 0 ? getContravariantInference(c, inference) : undefined;
2139
+ if (covariant !== undefined || contravariant !== undefined) {
2140
+ // Prefer the covariant inference when it isn't never or any, is assignable to some
2141
+ // contravariant candidate, and no type parameter constrained to this one conflicts.
2142
+ const preferCovariantType =
2143
+ covariant !== undefined &&
2144
+ (contravariant === undefined ||
2145
+ ((covariant.flags & (TypeFlags.Never | TypeFlags.Any)) === 0 &&
2146
+ someTypeAssignableFrom(c, covariant, inference.contraCandidates) &&
2147
+ noConflictingConstrainedInference(c, context, inference, covariant)));
2148
+ if (preferCovariantType) {
2149
+ inferredType = covariant;
2150
+ fallbackType = contravariant;
2151
+ } else {
2152
+ inferredType = contravariant;
2153
+ fallbackType = covariant;
2154
+ }
2155
+ } else if ((context.flags & InferenceFlags.NoDefault) !== 0) {
2156
+ // silentNeverType signals no inferences.
2157
+ inferredType = c.silentNeverType;
2158
+ } else {
2159
+ // No inferences: the default, with forward references to later type parameters erased.
2160
+ const defaultType = getDefaultFromTypeParameter(c, inference.typeParameter);
2161
+ if (defaultType !== undefined)
2162
+ inferredType = instantiateType(
2163
+ c,
2164
+ defaultType,
2165
+ new MergedTypeMapper(newBackreferenceMapper(c, context, index), context.nonFixingMapper),
2166
+ );
2167
+ }
2168
+ } else inferredType = getTypeFromInference(c, inference);
2169
+ inference.inferredType =
2170
+ inferredType ?? ((context.flags & InferenceFlags.AnyDefault) !== 0 ? c.anyType : c.unknownType);
2171
+ const constraint = getConstraintOfTypeParameter(c, inference.typeParameter);
2172
+ if (constraint !== undefined) {
2173
+ const instantiatedConstraint = instantiateType(c, constraint, context.nonFixingMapper);
2174
+ if (inferredType !== undefined) {
2175
+ const constraintWithThis = getTypeWithThisArgument(c, instantiatedConstraint, inferredType, false);
2176
+ if (context.compareTypes.compare(inferredType, constraintWithThis, false) === Ternary.False) {
2177
+ // A pure return type inference may still succeed without the constituents the constraint rejects.
2178
+ let filtered: Type | undefined = undefined;
2179
+ if (inference.priority === InferencePriority.ReturnType)
2180
+ filtered = mapType(c, inferredType, (t) =>
2181
+ context.compareTypes.compare(t, constraintWithThis, false) !== Ternary.False ? t : c.neverType,
2182
+ );
2183
+ inferredType = filtered !== undefined && (filtered.flags & TypeFlags.Never) === 0 ? filtered : undefined;
2184
+ }
2185
+ }
2186
+ if (inferredType === undefined)
2187
+ inferredType =
2188
+ fallbackType !== undefined &&
2189
+ context.compareTypes.compare(
2190
+ fallbackType,
2191
+ getTypeWithThisArgument(c, instantiatedConstraint, fallbackType, false),
2192
+ false,
2193
+ ) !== Ternary.False
2194
+ ? fallbackType
2195
+ : instantiatedConstraint;
2196
+ inference.inferredType = inferredType;
2197
+ }
2198
+ clearActiveMapperCaches(c);
2199
+ return inference.inferredType;
2200
+ }
2201
+
2202
+ function clearActiveMapperCaches(c: Checker): void {
2203
+ for (const cache of c.activeMapperCaches) if (cache !== undefined) cache.clear();
2204
+ for (const cache of c.activeMapperAliasCaches) if (cache !== undefined) cache.clear();
2205
+ }
2206
+
2207
+ /** Type ids below this bound pack in pairs into one exact number. */
2208
+ const VisitKeyIdLimit = 1 << 26;
2209
+
2210
+ /** invokeOnce's key for a pair of types: both ids in one number, or -1 when an id is too large. */
2211
+ function visitKey(source: Type, target: Type): number {
2212
+ const s = source.id;
2213
+ const t = target.id;
2214
+ return s < VisitKeyIdLimit && t < VisitKeyIdLimit ? s * VisitKeyIdLimit + t : -1;
2215
+ }
2216
+
2217
+ /** Maps forward references to later type parameters to `unknown`, for instantiating defaults. */
2218
+ function newBackreferenceMapper(c: Checker, context: InferenceContext, index: number): TypeMapper {
2219
+ return new ArrayToSingleTypeMapper(
2220
+ context.inferences.slice(index).map((i) => i.typeParameter),
2221
+ c.unknownType,
2222
+ );
2223
+ }
2224
+
2225
+ export function getInferredTypes(c: Checker, context: InferenceContext): Type[] {
2226
+ const result: Type[] = [];
2227
+ for (let i = 0; i < context.inferences.length; i++) result.push(getInferredType(c, context, i));
2228
+ return result;
2229
+ }
2230
+
2231
+ function getCovariantInference(c: Checker, inference: InferenceInfo, signature: Signature): Type {
2232
+ // Object and array literal candidates become one widened, normalized type.
2233
+ const candidates = unionObjectAndArrayLiteralCandidates(c, inference.candidates);
2234
+ // Widen literals when all inferences were to top-level occurrences, the type parameter has no
2235
+ // primitive constraint, and it was fixed or doesn't occur at top level in the return type.
2236
+ const primitiveConstraint =
2237
+ hasPrimitiveConstraint(c, inference.typeParameter) || isConstTypeVariable(c, inference.typeParameter, 0);
2238
+ const widenLiteralTypes =
2239
+ !primitiveConstraint &&
2240
+ inference.topLevel &&
2241
+ (inference.isFixed || !isTypeParameterAtTopLevelInReturnType(c, signature, inference.typeParameter));
2242
+ let baseCandidates = candidates;
2243
+ if (primitiveConstraint || widenLiteralTypes) {
2244
+ baseCandidates = [];
2245
+ for (const t of candidates)
2246
+ baseCandidates.push(primitiveConstraint ? getRegularTypeOfLiteralType(c, t) : getWidenedLiteralType(c, t));
2247
+ }
2248
+ // Positions implying a combined result infer a union, others a common supertype.
2249
+ const unwidenedType =
2250
+ (inference.priority & InferencePriority.PriorityImpliesCombination) !== 0
2251
+ ? getUnionTypeEx(c, baseCandidates, UnionReduction.Subtype, undefined, undefined)
2252
+ : getCommonSupertype(c, baseCandidates);
2253
+ return getWidenedType(c, unwidenedType);
2254
+ }
2255
+
2256
+ function getContravariantInference(c: Checker, inference: InferenceInfo): Type {
2257
+ return (inference.priority & InferencePriority.PriorityImpliesCombination) !== 0
2258
+ ? getIntersectionType(c, inference.contraCandidates)
2259
+ : getCommonSubtype(c, inference.contraCandidates);
2260
+ }
2261
+
2262
+ function someTypeAssignableFrom(c: Checker, source: Type, targets: Type[]): boolean {
2263
+ for (const t of targets) if (isTypeAssignableTo(c, source, t)) return true;
2264
+ return false;
2265
+ }
2266
+
2267
+ /** No other inference constrained to `inference`'s type parameter has a candidate not assignable to `covariant`. */
2268
+ function noConflictingConstrainedInference(
2269
+ c: Checker,
2270
+ context: InferenceContext,
2271
+ inference: InferenceInfo,
2272
+ covariant: Type,
2273
+ ): boolean {
2274
+ for (const other of context.inferences) {
2275
+ if (other !== inference && getConstraintOfTypeParameter(c, other.typeParameter) !== inference.typeParameter)
2276
+ continue;
2277
+ for (const t of other.candidates) if (!isTypeAssignableTo(c, t, covariant)) return false;
2278
+ }
2279
+ return true;
2280
+ }
2281
+
2282
+ function everyNonGenericObjectType(c: Checker, types: Type[]): boolean {
2283
+ for (const t of types) if (!isNonGenericObjectType(c, t)) return false;
2284
+ return true;
2285
+ }
2286
+
2287
+ function isObjectOrArrayLiteralType(t: Type): boolean {
2288
+ return (t.objectFlags & (ObjectFlags.ObjectLiteral | ObjectFlags.ArrayLiteral)) !== 0;
2289
+ }
2290
+
2291
+ function unionObjectAndArrayLiteralCandidates(c: Checker, candidates: Type[]): Type[] {
2292
+ if (candidates.length > 1) {
2293
+ const objectLiterals: Type[] = [];
2294
+ const result: Type[] = [];
2295
+ for (const t of candidates) {
2296
+ if (isObjectOrArrayLiteralType(t)) objectLiterals.push(t);
2297
+ else result.push(t);
2298
+ }
2299
+ if (objectLiterals.length !== 0) {
2300
+ result.push(getUnionTypeEx(c, objectLiterals, UnionReduction.Subtype, undefined, undefined));
2301
+ return result;
2302
+ }
2303
+ }
2304
+ return candidates;
2305
+ }
2306
+
2307
+ function hasPrimitiveConstraint(c: Checker, t: Type): boolean {
2308
+ let constraint = getConstraintOfTypeParameter(c, t);
2309
+ if (constraint === undefined) return false;
2310
+ if ((constraint.flags & TypeFlags.Conditional) !== 0) constraint = getConstraintFromConditionalType(c, constraint);
2311
+ return maybeTypeOfKind(
2312
+ constraint,
2313
+ TypeFlags.Primitive | TypeFlags.Index | TypeFlags.TemplateLiteral | TypeFlags.StringMapping,
2314
+ );
2315
+ }
2316
+
2317
+ export function getTypeFromInference(c: Checker, inference: InferenceInfo): Type | undefined {
2318
+ if (inference.candidates.length !== 0)
2319
+ return getUnionTypeEx(c, inference.candidates, UnionReduction.Subtype, undefined, undefined);
2320
+ if (inference.contraCandidates.length !== 0) return getIntersectionType(c, inference.contraCandidates);
2321
+ return undefined;
2322
+ }
2323
+
2324
+ export function getCommonSupertype(c: Checker, types: Type[]): Type {
2325
+ if (types.length === 1) return types[0]!;
2326
+ // Remove nullable types, find the supertype, and add them back.
2327
+ let primaryTypes = types;
2328
+ if (c.strictNullChecks) {
2329
+ primaryTypes = [];
2330
+ for (const t of types) primaryTypes.push(filterType(c, t, (u) => (u.flags & TypeFlags.Nullable) === 0));
2331
+ }
2332
+ const supertype = literalTypesWithSameBaseType(c, primaryTypes)
2333
+ ? getUnionType(c, primaryTypes)
2334
+ : getSingleCommonSupertype(c, primaryTypes);
2335
+ let same = true;
2336
+ for (let i = 0; i < types.length; i++) if (primaryTypes[i]! !== types[i]!) same = false;
2337
+ if (same) return supertype;
2338
+ return getNullableType(c, supertype, getCombinedTypeFlags(types) & TypeFlags.Nullable);
2339
+ }
2340
+
2341
+ function getSingleCommonSupertype(c: Checker, types: Type[]): Type {
2342
+ // The leftmost type no type to its right is a strict supertype of, if it's a strict supertype of
2343
+ // all others; otherwise the same with regular supertypes.
2344
+ let candidate: Type | undefined = undefined;
2345
+ for (const t of types) if (candidate === undefined || isTypeStrictSubtypeOf(c, candidate, t)) candidate = t;
2346
+ let strictSupertype = true;
2347
+ for (const t of types) {
2348
+ if (t !== candidate && !isTypeStrictSubtypeOf(c, t, candidate!)) {
2349
+ strictSupertype = false;
2350
+ break;
2351
+ }
2352
+ }
2353
+ if (strictSupertype) return candidate!;
2354
+ candidate = undefined;
2355
+ for (const t of types) if (candidate === undefined || isTypeSubtypeOf(c, candidate, t)) candidate = t;
2356
+ return candidate!;
2357
+ }
2358
+
2359
+ /** The leftmost type no type to its right is a subtype of. */
2360
+ export function getCommonSubtype(c: Checker, types: Type[]): Type {
2361
+ let subtype: Type | undefined = undefined;
2362
+ for (const t of types) if (subtype === undefined || isTypeSubtypeOf(c, t, subtype)) subtype = t;
2363
+ return subtype!;
2364
+ }
2365
+
2366
+ function getCombinedTypeFlags(types: Type[]): TypeFlags {
2367
+ let flags = TypeFlags.None;
2368
+ for (const t of types) flags |= (t.flags & TypeFlags.Union) !== 0 ? getCombinedTypeFlags(typesOf(t)) : t.flags;
2369
+ return flags;
2370
+ }
2371
+
2372
+ function literalTypesWithSameBaseType(c: Checker, types: Type[]): boolean {
2373
+ let commonBaseType: Type | undefined = undefined;
2374
+ for (const t of types) {
2375
+ if ((t.flags & TypeFlags.Never) !== 0) continue;
2376
+ const baseType = getBaseTypeOfLiteralType(c, t);
2377
+ if (commonBaseType === undefined) commonBaseType = baseType;
2378
+ if (baseType === t || baseType !== commonBaseType) return false;
2379
+ }
2380
+ return true;
2381
+ }
2382
+
2383
+ // ---- Conditional types
2384
+
2385
+ /** A mapper from a conditional type's `infer` type parameters to their inferences. */
2386
+ export function inferTypesForConditional(
2387
+ c: Checker,
2388
+ root: ConditionalRoot,
2389
+ checkType: Type,
2390
+ extendsType: Type,
2391
+ mapper: TypeMapper | undefined,
2392
+ checkTypeDeferred: boolean,
2393
+ ): TypeMapper | undefined {
2394
+ // The constraints of `infer` type parameters may refer to other roots or to what `mapper` maps,
2395
+ // so the non-fixing mapper combines with `mapper`.
2396
+ const context = createInferenceContext(c, root.inferTypeParameters, undefined, InferenceFlags.None, undefined);
2397
+ if (mapper !== undefined) context.nonFixingMapper = combineTypeMappers(c, context.nonFixingMapper, mapper);
2398
+ // Inferences from constraints could eagerly resolve what should defer; contravariance is always strict.
2399
+ if (!checkTypeDeferred)
2400
+ inferTypes(
2401
+ c,
2402
+ context.inferences,
2403
+ checkType,
2404
+ extendsType,
2405
+ InferencePriority.NoConstraints | InferencePriority.AlwaysStrict,
2406
+ false,
2407
+ );
2408
+ return context.mapper;
2409
+ }
2410
+
2411
+ /** Caches and stacks for inference, contextual typing and call resolution. */
2412
+ export class InferenceCaches {
2413
+ /**
2414
+ * Contextual types pushed for nodes being checked, innermost last. The first `contextualDepth`
2415
+ * entries are live; popping keeps the slots after them for reuse.
2416
+ */
2417
+ readonly contextualNodes: Node[] = [];
2418
+ readonly contextualTypes: (Type | undefined)[] = [];
2419
+ readonly contextualIsCache: boolean[] = [];
2420
+ contextualDepth = 0;
2421
+ /** Inference contexts pushed for arguments being checked, innermost last; `inferenceDepth` are live. */
2422
+ readonly inferenceNodes: Node[] = [];
2423
+ readonly inferenceContexts: (InferenceContext | undefined)[] = [];
2424
+ inferenceDepth = 0;
2425
+ readonly optionalCallSignatures = new Map<Signature, Map<string, Signature>>();
2426
+ readonly discriminatedContextualTypes = new Map<string, Type>();
2427
+ /** `discriminatedContextualTypes` by node and type id packed into one number, when they fit. */
2428
+ readonly discriminatedContextualTypesById = new Map<number, Type>();
2429
+ /** For union contextual types, what each constituent has for a missing optional property (discriminateTypeByObjectLiteral). */
2430
+ readonly missingPropertyStates = new Map<Type, Map<string, number>>();
2431
+ readonly contextFreeTypes = new Map<Node, Type>();
2432
+ readonly reverseMapped = new Map<string, Type | undefined>();
2433
+ readonly reverseHomomorphicMapped = new Map<string, Type | undefined>();
2434
+ /** inferReverseMappedType's recursion stacks; the first `reverseStackDepth` entries of each are live. */
2435
+ readonly reverseSourceStack: Type[] = [];
2436
+ readonly reverseTargetStack: Type[] = [];
2437
+ reverseStackDepth = 0;
2438
+ reverseExpandingFlags: number = ExpandingFlags.None;
2439
+ }
2440
+
2441
+ // ---- Constraints of `infer` type parameters
2442
+
2443
+ /**
2444
+ * Maps the type parameters of a type reference to its type arguments, resolving them (and filling
2445
+ * in defaults) only when a type parameter is mapped.
2446
+ */
2447
+ class TypeArgumentMapper extends TypeMapper {
2448
+ readonly c: Checker;
2449
+ readonly typeArgumentNodes: readonly Node[];
2450
+ readonly typeParameters: readonly Type[];
2451
+ filled: Type[] | undefined = undefined;
2452
+
2453
+ constructor(c: Checker, typeArgumentNodes: readonly Node[], typeParameters: readonly Type[]) {
2454
+ super();
2455
+ this.c = c;
2456
+ this.typeArgumentNodes = typeArgumentNodes;
2457
+ this.typeParameters = typeParameters;
2458
+ }
2459
+
2460
+ map(t: Type): Type {
2461
+ const index = this.typeParameters.indexOf(t);
2462
+ if (index < 0) return t;
2463
+ if (index < this.typeArgumentNodes.length) return getTypeFromTypeNode(this.c, this.typeArgumentNodes[index]!);
2464
+ if (this.filled === undefined) {
2465
+ const typeArguments: Type[] = [];
2466
+ for (const n of this.typeArgumentNodes) typeArguments.push(getTypeFromTypeNode(this.c, n));
2467
+ this.filled = fillMissingTypeArguments(
2468
+ this.c,
2469
+ typeArguments,
2470
+ this.typeParameters,
2471
+ getMinTypeArgumentCount(this.c, this.typeParameters),
2472
+ false,
2473
+ );
2474
+ }
2475
+ return this.filled[index]!;
2476
+ }
2477
+ }
2478
+
2479
+ /**
2480
+ * The constraint an `infer T` position implies, e.g. `unknown[]` in a rest position; with
2481
+ * `omitTypeReferences`, `Foo<infer T>` implies none.
2482
+ */
2483
+ export function getInferredTypeParameterConstraint(c: Checker, t: Type, omitTypeReferences = false): Type | undefined {
2484
+ const inferences: Type[] = [];
2485
+ const symbol = t.symbol;
2486
+ if (symbol !== undefined)
2487
+ for (const declaration of symbol.declarations) {
2488
+ if (declaration.parent === undefined || declaration.parent.kind !== SyntaxKind.InferType) continue;
2489
+ let child: Node = declaration.parent;
2490
+ let parent = child.parent;
2491
+ while (parent !== undefined && parent.kind === SyntaxKind.ParenthesizedType) {
2492
+ child = parent;
2493
+ parent = child.parent;
2494
+ }
2495
+ if (parent === undefined) continue;
2496
+ switch (parent.kind) {
2497
+ case SyntaxKind.TypeReference: {
2498
+ if (omitTypeReferences) break;
2499
+ // `Foo<infer T>` takes the constraint of Foo's corresponding type parameter.
2500
+ const typeArgumentNodes = (parent as TypeReferenceNode).typeArguments;
2501
+ const typeParameters = getTypeParametersForTypeReference(c, parent);
2502
+ if (typeArgumentNodes === undefined || typeParameters === undefined) break;
2503
+ const index = typeArgumentNodes.nodes.indexOf(child);
2504
+ if (index < 0 || index >= typeParameters.length) break;
2505
+ const declaredConstraint = getConstraintOfTypeParameter(c, typeParameters[index]!);
2506
+ if (declaredConstraint === undefined) break;
2507
+ // Constraints referencing the type parameter itself are discarded.
2508
+ const constraint = instantiateType(
2509
+ c,
2510
+ declaredConstraint,
2511
+ new TypeArgumentMapper(c, typeArgumentNodes.nodes, typeParameters),
2512
+ );
2513
+ if (constraint !== t) inferences.push(constraint);
2514
+ break;
2515
+ }
2516
+ case SyntaxKind.Parameter:
2517
+ if ((parent as ParameterDeclaration).dotDotDotToken !== undefined)
2518
+ inferences.push(createArrayType(c, c.unknownType));
2519
+ break;
2520
+ case SyntaxKind.RestType:
2521
+ inferences.push(createArrayType(c, c.unknownType));
2522
+ break;
2523
+ case SyntaxKind.NamedTupleMember:
2524
+ if ((parent as NamedTupleMember).dotDotDotToken !== undefined)
2525
+ inferences.push(createArrayType(c, c.unknownType));
2526
+ break;
2527
+ case SyntaxKind.TemplateLiteralTypeSpan:
2528
+ inferences.push(c.stringType);
2529
+ break;
2530
+ case SyntaxKind.TypeParameter:
2531
+ if (parent.parent !== undefined && parent.parent.kind === SyntaxKind.MappedType)
2532
+ inferences.push(c.stringNumberSymbolType);
2533
+ break;
2534
+ case SyntaxKind.MappedType: {
2535
+ // `{ [P in K]: X } extends { [Q in L]: infer U }` constrains U to X with P replaced by K.
2536
+ const mapped = parent as MappedTypeNode;
2537
+ const conditional = parent.parent;
2538
+ if (
2539
+ mapped.type !== undefined &&
2540
+ mapped.type === declaration.parent &&
2541
+ conditional !== undefined &&
2542
+ conditional.kind === SyntaxKind.ConditionalType &&
2543
+ (conditional as ConditionalTypeNode).extendsType === parent &&
2544
+ (conditional as ConditionalTypeNode).checkType.kind === SyntaxKind.MappedType &&
2545
+ ((conditional as ConditionalTypeNode).checkType as MappedTypeNode).type !== undefined
2546
+ ) {
2547
+ const checkMappedType = (conditional as ConditionalTypeNode).checkType as MappedTypeNode;
2548
+ const nodeType = getTypeFromTypeNode(c, checkMappedType.type!);
2549
+ const checkMappedTypeParameter = checkMappedType.typeParameter;
2550
+ const mapper = new SimpleTypeMapper(
2551
+ getDeclaredTypeOfTypeParameter(c, getSymbolOfDeclaration(c, checkMappedTypeParameter)!),
2552
+ checkMappedTypeParameter.constraint !== undefined
2553
+ ? getTypeFromTypeNode(c, checkMappedTypeParameter.constraint)
2554
+ : c.stringNumberSymbolType,
2555
+ );
2556
+ inferences.push(instantiateType(c, nodeType, mapper));
2557
+ }
2558
+ break;
2559
+ }
2560
+ }
2561
+ }
2562
+ return inferences.length !== 0 ? getIntersectionType(c, inferences) : undefined;
2563
+ }
2564
+
2565
+ function getTypeParametersForTypeReference(c: Checker, node: Node): readonly Type[] | undefined {
2566
+ if (isErrorType(c, getTypeFromTypeNode(c, node))) return undefined;
2567
+ const symbol = c.resolvedSymbols.get(node.id);
2568
+ if (symbol === undefined || symbol === c.unknownSymbol) return undefined;
2569
+ if ((symbol.flags & (SymbolFlags.Class | SymbolFlags.Interface)) !== 0)
2570
+ return getDeclaredTypeOfClassOrInterface(c, getMergedSymbol(c, symbol)).localTypeParameters();
2571
+ if ((symbol.flags & SymbolFlags.TypeAlias) !== 0) {
2572
+ getDeclaredTypeOfSymbol(c, symbol);
2573
+ return c.symbolLinks(symbol).typeParameters;
2574
+ }
2575
+ return undefined;
2576
+ }