我試圖使用作為變量來定位對象中的值,基本上是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'.
下面是代碼,最后一行是我得到typescript錯誤的代碼(使用嚴格類型)
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
您應該為
myName
使用正確的類型:這還有一個好處,就是當您輸入錯誤時會出現編譯錯誤,例如,這將失敗: