In typescript, How to access object key(property) using variable?
for example:
interface Obj {
a: Function;
b: string;
}
let obj: Obj = {
a: function() { return 'aaa'; },
b: 'bbbb'
}
for(let key in obj) {
console.log(obj[key]);
}
but typescript throw below error message:
'TS7017 Element implicitly has an 'any' type because type 'obj' has no index signature'
How to fix it?
I tried your code above as a quick test in WebStorm, and it compiled and ran without error. If you are using a version of Typescript before 2.0, I suggest trying Typescript 2.0 or higher.
To compile this code with
--noImplicitAny
, you need to have some kind of type-checked version ofObject.keys(obj)
function, type-checked in a sense that it's known to return only the names of properties defined inobj
.There is no such function built-in in TypeScript AFAIK, but you can provide your own: