interface MyData {
id: number;
name: string;
}
const myData: MyData=
{
id: 1,
name: 'hoge',
}
Object.keys(myData).map((key) => {
console.log(myData[key]); // ★ ここでエラー(TS7053)となります。
});
TS Playground
https://bit.ly/3KxxBgx
このようなエラーが表示されます
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'MyData'.
No index signature with a parameter of type 'string' was found on type 'MyData'.(7053)
Object.keys(myData).map((key) => {
console.log(myData[key]); // ★ ここでエラー(TS7053)となります。
});
↓ 次のように修正します
(Object.keys(myData) as (keyof MyData)[]).map((key) => {
console.log(myData[key]);
});
Object.entries(myData).map(([key, value]) => {
console.log( '● key, value' );
console.log( `${key} : ${value}` );
})
https://stackoverflow.com/questions/59545011/object-with-generic-keys-in-typescript
MyInterface の メンバ名であることを保証する関数を作成します。
name , address, email は適宜書き換えること
function isProperty(value: string): value is (keyof MyInterface){
return value === 'name' || value === 'address' || value === 'email';
}