TypeScriptのIndex Signatureでプロパティに制限をかけたかったので、今更ながらよくよく調べてみた

Index Signatureを使用することでプロパティの型を指定することができる。 例えば、 interface BodyType { [key: number]: { min: number, max: number } } const body:BodyType = { String: { min: 0, max: 230 }, 1: { min:0, max:300 } } console.log(body.String.min)} ] 上記のようにnumber型という風に明示的に宣言することで、Stringという文字列をkeyに指定したことでエラーを吐かせることが可能である。 type '{ hello: { min: number; max: number; }; 1: { min: number; max: number; }; }' is not assignable to type 'BodyType'. Object literal may only specify known properties, and 'hello' does not exist in type 'BodyType'....

投稿日 · 2023-09-26 · 更新日 · 2024-06-07 · 1 分 · nove-b