最終更新:2023-07-27 (木) 17:00:32 (274d)
TypeScript/型アサーション
Top / TypeScript / 型アサーション
コンパイラに対し型を表明する機能 (コンパイル時の処理)
https://typescript-jp.gitbook.io/deep-dive/type-system/type-assertion
例
- const canvas = document.getElementById?("id") as HTMLCanvasElement
記法
- 2種類
hoge as string
<string>hoge
- JSXでも<componentName>が使えるため一貫性のためにas fooを使うことをお勧めします
メモ
- キャストに似ているが、データが再構築されるわけではない。
- 一応<type> valueの書き方もある
<any>window
ダブルアサーション
- 一度anyにしてコンパイラに文句を言わせなくする
- https://typescript-jp.gitbook.io/deep-dive/type-system/type-assertion#daburuasshon
- as any as
- as unknown as