Type 'X' is not assignable to type 'Y'
TypeScriptで型が一致しない場合に発生するコンパイルエラー
概要
Type 'X' is not assignable to type 'Y' は、TypeScriptで変数や引数に互換性のない型の値を代入しようとした場合に発生するコンパイルエラーです。TypeScriptの型システムによる静的型チェックで検出されます。
エラーメッセージ
Type 'string' is not assignable to type 'number'.
Type 'null' is not assignable to type 'string'.
Type '{ name: string; }' is not assignable to type 'User'.
Property 'id' is missing in type '{ name: string; }' but required in type 'User'.
Argument of type 'string | undefined' is not assignable to parameter of type 'string'.
Type 'undefined' is not assignable to type 'string'.
原因
- 基本型の不一致: string、number、booleanなどの型が異なる
- nullやundefinedの扱い: strictNullChecksが有効な場合
- オブジェクト型のプロパティ不足: 必須プロパティが欠けている
- 配列/オブジェクトの型不一致: 要素の型が異なる
- ユニオン型の絞り込み不足: 型ガードがない
解決策
1. 基本型の変換
| |
2. null/undefinedを許容する
| |
3. 非nullアサーション演算子
| |
4. オブジェクト型のプロパティを追加
| |
5. 型ガードで絞り込む
| |
6. 型アサーション(キャスト)
| |
7. ジェネリクスの型パラメータ
| |
8. 配列の型
| |
9. 関数の引数・戻り値
| |
10. as constで厳密なリテラル型
| |
tsconfig.jsonの設定
| |
TypeScript の他のエラー
この記事は役に立ちましたか?