Search code examples
typescriptindex-signature

How to avoid implicit any when iterating over object keys in Typescript


The following code:

interface Foo {
  bar: string;
  qux: string;
  baz: number;
}

const foo: Foo = {
  bar: '42',
  qux: 'baz',
  baz: 5
};

const keysToIterateOver = [ 'bar', 'qux' ];

keysToIterateOver.forEach(key => foo[key] = 'newStringValue');

gives TypeScript compile error:

Element implicitly has an 'any' type because type 'Foo' has no index signature

How can I tell the compiler that I am only iterating over keys that have a string value and can safely reassign their values?


Solution

  • You can achieve this by specifying the type of keysToIterateOver:

    const keysToIterateOver: (keyof Foo)[] = [ 'bar', 'qux' ];
    

    Otherwise the inferred type is string[], hence the error