eyvaz
eyvaz

Reputation: 171

Typescript doesn't raise error when index types doesn't match

Why typescript doesn't raise error or warning in this code? In map["xx"] index type is string but in map signature it's number. should I set any config in tsconfig?

let map: { [index: number]: string } = { };

map["xx"] = "2000";

Upvotes: 1

Views: 418

Answers (1)

Mic Fung
Mic Fung

Reputation: 5692

If you did not enable strict: true or noImplicitAny: true in tsconfig.json, it is an expected behaviour as the index in bracket notation is treated as any.

You can read this issue for details:

https://github.com/microsoft/TypeScript/issues/7660

Here is the playground you can see the result before/after enable noImplicitAny:

  1. Without noImplicitAny, no error
  2. With noImplicitAny, will prompt error on map["xx"]

P.S. You can either use noImplicitAny: true or strict: true where strict mode includes noImplicitAny and 6 more checking implicitly. More details can be found in the typescript doc.


Although strict mode is not enabled by default due to migration and legacy problem, it is recommended by Typescript team to enable strict: true in their playground comment.

Yes, we know, the defaults for TypeScript's tsconfig do not have strict turned on. However, at every chance we can the team recommends that users try migrate towards having strict mode enabled in their configs.

Upvotes: 2

Related Questions