Reputation: 171
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
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
:
noImplicitAny
, no errornoImplicitAny
, 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