Why is this allowed by TypeScript? I specified a numeric index. Why can I use a string as an index? Visual studio doesn\'t report an error.
interface StringA
Problem
It's because the compiler is still allowing implicit any
types which can happen when accessing a property of an object by using an index:
// Example 1
let dictionary: { [index: number]: string };
let myStringTypedVar = dictionary[5]; // implicitly typed as "string"
let myAnyTypedVar = dictionary["prop"]; // implicitly typed as "any"
// Example 2
let myNumberTypedVar = 5;
let myAnyTypedVar = myNumberTypedVar["prop"]; // implicitly typed as "any"
Fix: Compile with --noImplictAny
If you compile your example with --noImplictAny
then it will error:
tsc --noImplicitAny example.ts
Outputs:
example.ts(8,9): error TS7017: Index signature of object type implicitly has an 'any' type.
I would recommend always compiling with --noImplicitAny
. In Visual Studio, you can turn on --noImplictAny
by unchecking "Allow implicit 'any' types" in the project properties' typescript build tab:
Or by adding "noImplicitAny": "true"
to compilerOptions
in tsconfig.json
.