【发布时间】:2022-12-19 20:38:50
【问题描述】:
我试图用作变量来定位对象中的值,基本上是 console.log(myobj.name) 但使用变量而不是名称,例如
const myProperty = name:string
console.log(myObj[myProperty])
下面的完整详细信息(包括接口)
代码运行但我在 VSCODE 中收到以下错误。
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Details'.
下面是代码,最后一行是我收到打字稿错误的代码(使用严格类型)
interface Details {
id:number,
name:string,
email:string
}
interface Items {
[key: string]: Details[],
}
const items: Items = {
"blackberry":[
{
id: 1,
name: 'John Doe',
email: 'john@doe.de'
},{
id: 2,
name: 'Brad',
email: 'lorem@ipsum.com',
}
],
"orange":[{
id: 4,
name: 'Barry',
email: 'john@doe.de'
}
]
}
const myName:string = "name"
const myIx:string = "orange"
// console.log(items[myIx])
console.log(items[myIx][0].name)
console.log(items[myIx][0][myName]) // code runs but TS error here in VScode
【问题讨论】:
标签: javascript typescript indexing javascript-objects