Upgrade to Pro — share decks privately, control downloads, hide ads and more …

TypeScriptはどのようにどこまで推論できるのか ─ とにかく as は禁止で

Sponsored · Ship Features Fearlessly Turn features on and off without deploys. Used by thousands of Ruby developers.

TypeScriptはどのようにどこまで推論できるのか ─ とにかく as は禁止で

TSKaigi 2026 Sponser Session Talk

- Contextual Type
- 型パラメータ推論
- 制御フロー解析
- asは全部禁止するべきか???? (as const除く)

Avatar for ypresto

ypresto

May 23, 2026

More Decks by ypresto

Other Decks in Technology

Transcript

  1. 逆方向:Contextual Type impl: ① arrow fn 解決→getContextualType: checkFunctionExpressionOrObjectLiteralMethod → contextuallyCheck…

    → getContextualSignature → getApparentTypeOfContextualType → getContextualType / ② 親をたどる: getContextualTypeForJsxAttribute / ③ e へ降ろす: assignContextualParameterTypes(lazy: getContextuallyTypedParameterType) © LayerX Inc. 6
  2. 当たり前に通るけど、Contextual Typeのおかげ impl: 型引数を contextual から: inferTypeArguments(contextual→戻り値型へ推論) / widen 抑制:

    getWidenedLiteralTypeForInitializer / isLiteralOfContextualType / ちなみに [] は any[] になるようです (never[]じゃなかったっけ...) © LayerX Inc. 7
  3. ところで、型パラメータの解決ルール impl: instantiateContextualType (nonFixingMapper で推論途中の T を反映) / inferTypeArguments /

    候補集め inferTypes: 引数→param ・ 戻り値 →return(低優先度) / getInferredType(候補が無ければ default / constraint) © LayerX Inc. 下記の優先順でTを推論する 引数: 'click' ← 採用 返り値のContextual Type: 'click' | 'hover' 8
  4. 型パラメータ推論とNoInfer impl: isNoInferType (= constraint が unknown の substitution type)

    / 候補集めをブロック (inferFromTypes) / 確定後は素の T に解決 © LayerX Inc. 下記の優先順でTを推論する 引数: NoInferなので対象外 返り値のContextual Type: 'click' | 'hover' ← 採用 9
  5. 最近は代入やComputed Propertyも絞れるように進化..! impl: narrowType の inline 展開 / isConstantReference /

    getDiscriminantPropertyAccess / getCandidateDiscriminantPropertyAccess / isMatchingReference © LayerX Inc. 11
  6. 型パズル難しい © LayerX Inc. form.getValues(): Tを返す → covariant 共変 (Tがより大きければ代入できる)

    form.setValue(): Tを受け取る → contravariant 反変 (Tがより小さければ代入できる) 両方合わせて → invariant: Tは完全に同じでないとダメ 14