I am trying to use as a variable to locate a value in an object, basically console.log(myobj.name) but use a variable instead of name e.g.
const myProperty = name:string
console.log(myObj[myProperty])
full details below (including interfaces)
The code runs but I get the following error in VSCODE.
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Details'.
below is the code the very last line is the one where I get the typescript error (using strict types)
interface Details {
id:number,
name:string,
email:string
}
interface Items {
[key: string]: Details[],
}
const items: Items = {
"blackberry":[
{
id: 1,
name: 'John Doe',
email: '[email protected]'
},{
id: 2,
name: 'Brad',
email: '[email protected]',
}
],
"orange":[{
id: 4,
name: 'Barry',
email: '[email protected]'
}
]
}
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
CodePudding user response:
You should use the correct type for myName
:
const myName: keyof Details = "name"
This also has the advantage, that you get a compile error when you have a typo, e.g. this will fail:
const myName: keyof Details = "Name"
CodePudding user response:
Typescript sees a string passed with object[str]
as being able to all kinds of values. You can set the myIx
to an enum to force it to be one of the actually existing keys within the interface
or the quick and dirty fix can be to cast it to any like this (items[myIx][0] as any)[myName]