Shubham
Shubham

Reputation: 1793

How to access keys of javascript objects dynamically in typescript

interface IObj { 
    fname: string;
    lname: string;
}

const obj: IObj = <IObj>{};

const array: string[] = ['fname', 'lname'];

array.forEach((key: string, index: number) => {
    obj[key] = `${index}`; // Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'IObj'.
});

I want to access object keys dynamically. But typescript is not letting me do it. Is there any way to achieve is in typescript.

Upvotes: 0

Views: 61

Answers (1)

kaya3
kaya3

Reputation: 51037

You declared array as type string[], and key as type string. If you want Typescript to know these strings are actually keys of IObj, then tell it that:

const array: (keyof IObj)[] = ['fname', 'lname'];

array.forEach((key: keyof IObj, index: number) => {
    obj[key] = `${index}`;
});

Playground Link

Upvotes: 3

Related Questions