必須プロパティの書き忘れエラーの原因と直し方
interfaceで定義した必須プロパティを、オブジェクトリテラルで指定し忘れたときに出るエラーです。1つでも足りないプロパティがあれば、その型の値として代入できません。
エラーメッセージの読み方
main.ts(5,7): error TS2741: Property 'age' is missing in type '{ name: string; }' but required in type 'User'.
main.ts- ファイル名
5- 行番号
7- 列番号 — この位置でtscが検査に失敗しました
TS2741- エラーコード — 検索するとTypeScriptの解説が見つかります
Property 'age' is missing in type '{ name: string; }' but required in type 'User'.- 内容 — 期待していたもの、または受け付けられなかったもの
このエラーが出る典型パターン
パターン1
1 interface User { 2 name: string; 3 age: number; 4 } 5 const u: User = { name: "Al" } ; ^ 6 console.log(u.age);
main.ts(5,7): error TS2741: Property 'age' is missing in type '{ name: string; }' but required in type 'User'.
Userにはageも必須プロパティとして定義されています。nameだけでは型を満たせません。
直し方: { name: "Al" } を { name: "Al", age: 30 } にします。
広告
広告スロット(未設定)
パターン2
1 interface Point { 2 x: number; 3 y: number; 4 } 5 const p: Point = { x: 1 } ; ^ 6 console.log(p.y);
main.ts(5,7): error TS2741: Property 'y' is missing in type '{ x: number; }' but required in type 'Point'.
Pointはxとyの両方が必須です。yを省略するとその型として代入できません。
直し方: { x: 1 } を { x: 1, y: 2 } にします。
パターン3
1 interface Item { 2 name: string; 3 price: number; 4 } 5 const item: Item = { price: 500 } ; ^ 6 console.log(item.price);
main.ts(5,7): error TS2741: Property 'name' is missing in type '{ price: number; }' but required in type 'Item'.
Itemにはnameも必須です。priceだけでは必要なプロパティが揃っていません。
直し方: { price: 500 } を { name: "Pen", price: 500 } にします。
よくある誤解
「一部のプロパティだけ先に埋めて、あとから追加すればいい」という感覚はTypeScriptのオブジェクトリテラルには通用しません。型に必須と宣言されたプロパティは、作成の時点ですべて揃っている必要があります。
まとめ
必須プロパティの書き忘れエラーの原因と直し方は初級でつまずきやすい項目です。上の3パターンを実際に手で直すと、エラーメッセージのどこを読めばよいかが掴めます。