简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM