19
votes

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?

5

5 Answers

15
votes

To compile this code with --noImplicitAny, you need to have some kind of type-checked version of Object.keys(obj) function, type-checked in a sense that it's known to return only the names of properties defined in obj.

There is no such function built-in in TypeScript AFAIK, but you can provide your own:

interface Obj {
    a: Function;
    b: string;
}

let obj: Obj = {
    a: function() { return 'aaa'; },
    b: 'bbbb'
};


function typedKeys<T>(o: T): (keyof T)[] {
    // type cast should be safe because that's what really Object.keys() does
    return Object.keys(o) as (keyof T)[];
}


// type-checked dynamic property access
typedKeys(obj).forEach(k => console.log(obj[k]));

// verify that it's indeed typechecked
typedKeys(obj).forEach(k => {
    let a: string = obj[k]; //  error TS2322: Type 'string | Function' 
                           // is not assignable to type 'string'.
                          //  Type 'Function' is not assignable to type 'string'.
});
6
votes

You can also do something like this:

const keyTyped = key as keyof typeof Obj;
const value = Obj[keyTyped];
6
votes

I found using keyOf to be the easiest solution

const logKey = (key: keyof Obj) => {
    console.log(obj[key])
}

for(let key in obj) {
    logKey(key)
}
0
votes

You can use extra function for iteration. TS infers type inside function in a more meaningful way:

interface Obj {
    a: Function;
    b: string;
}

let obj: Obj = {
    a: function () { return 'aaa'; },
    b: 'bbbb'
}

const iterator = <T extends Obj>(obj: T) => {
    for (let key in obj) {
        console.log(obj[key]);
    }
}

Playground

-2
votes

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.