typescriptindex-signature

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?


Solution

  • Try typing your array :

    const myObj = {
      foo: "string",
      bar: 123,
      baz: "important stuff"
    };
    
    const myArray: (keyof typeof myObj)[] = ['foo', 'bar']
    
    myArray.forEach(...)