MrMamen
MrMamen

Reputation: 389

Index signature for iteration in typescript

We can all see that this code is valid javascript:

const myObj = {
  foo: "string",
  bar: 123,
  baz: "important stuff"
};

['foo', 'bar'].forEach((key) => {
  delete myObj[key];
});

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ foo: string; bar: number; baz: string; }'. No index signature with a parameter of type 'string' was found on type '{ foo: string; bar: number; baz: string; }'.

So what's the best way of doing this TypeScript compatible?

Upvotes: 0

Views: 1175

Answers (2)

JeromeBu
JeromeBu

Reputation: 1159

Try typing your array :

const myObj = {
  foo: "string",
  bar: 123,
  baz: "important stuff"
};

const myArray: (keyof typeof myObj)[] = ['foo', 'bar']

myArray.forEach(...)

Upvotes: 1

MrMamen
MrMamen

Reputation: 389

One workaround is:

(['foo', 'bar'] as (keyof typeof myObj)[]).forEach((key) => {
  delete myObj[key];
});

But it does not prevent typing errors in the array-strings.

Upvotes: 0

Related Questions