インデックスシグネチャと矛盾する型のプロパティを宣言するとエラーになる
[key: string]: numberのようなインデックスシグネチャを持つinterfaceでは、個別に宣言する具体的なプロパティも、インデックスシグネチャの型と互換性がなければ宣言できません。
エラーメッセージの読み方
main.ts(3,3): error TS2411: Property 'name' of type 'string' is not assignable to 'string' index type 'number'.
main.ts- ファイル名
3- 行番号
3- 列番号 — この位置でtscが検査に失敗しました
TS2411- エラーコード — 検索するとTypeScriptの解説が見つかります
Property 'name' of type 'string' is not assignable to 'string' index type 'number'.- 内容 — 期待していたもの、または受け付けられなかったもの
このエラーが出る典型パターン
パターン1
1 interface Dict { 2 [key: string]: number; 3 name: string ; ^ 4 } 5 console.log("ok");
main.ts(3,3): error TS2411: Property 'name' of type 'string' is not assignable to 'string' index type 'number'.
インデックスシグネチャは全プロパティがnumber型であることを要求します。nameをstring型で宣言すると矛盾します。
直し方: name: string を count: number にします。
広告
広告スロット(未設定)
パターン2
1 interface Scores { 2 [key: string]: number; 3 label: boolean; ^ 4 } 5 console.log("ok");
main.ts(3,3): error TS2411: Property 'label' of type 'boolean' is not assignable to 'string' index type 'number'.
labelをboolean型で宣言すると、number型を要求するインデックスシグネチャと矛盾します。
直し方: label: boolean を total: number にします。
パターン3
1 interface Flags { 2 [key: string]: boolean; 3 count: number ; ^ 4 } 5 console.log("ok");
main.ts(3,3): error TS2411: Property 'count' of type 'number' is not assignable to 'string' index type 'boolean'.
このインデックスシグネチャはboolean型を要求します。countをnumber型で宣言すると矛盾します。
直し方: count: number を active: boolean にします。
よくある誤解
「個別に書いたプロパティは、インデックスシグネチャより優先されるはず」という考えは誤りです。TypeScriptは両方が矛盾なく共存できることを要求し、型が食い違う時点でinterfaceの宣言自体をエラーにします。
まとめ
インデックスシグネチャと矛盾する型のプロパティを宣言するとエラーになるは中級でつまずきやすい項目です。上の3パターンを実際に手で直すと、エラーメッセージのどこを読めばよいかが掴めます。