Esa Toivola
Esa Toivola

Reputation: 1538

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?

Upvotes: 0

Views: 1044

Answers (2)

Aleksey L.
Aleksey L.

Reputation: 37986

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

Upvotes: 2

Suren Srapyan
Suren Srapyan

Reputation: 68665

Compiler can not detect dynamic property's type and considers the property to have any type. As a workaround you can write your interface with indexer. This will tell to the compiler that any dynamic accessed property with [] indexer contains string or number and the foo[key] = 'newStringValue' assignment is correct.

interface Foo {
    [prop: string]: string | number,
    bar: string;
    qux: string;
    baz: number;
}

Another variant is to remove the "noImplicitAny": true, from tsconfig.json file, but it is not the best one.

Upvotes: 0

Related Questions