0
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.

2
  • 2
    Curse it, god darn typescript not letting you do it. Commented Nov 29, 2019 at 4:28
  • 1
    @Spangle tried cursing it, didn't fix my problem ;) Any other solutions. Commented Nov 29, 2019 at 4:30

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

3 Comments

There's no need to specify types in the forEach callback if you don't want to, TS can infer them just fine
Yes, indeed; I was just directly adapting the code to change string to the more specific type.
@kaya3 Thanks for the quick response. Just one more question, Suppose I have one more object obj2 and I want to assign its value to obj. How should I proceed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.