I have the following code and noImplicitAny:true
in tsconfig
:
let o = {a: 3};
// works fine
o['a'] = 3;
// reports an error
// Error:(4, 1) TS7017:Index signature of object type implicitly has an 'any' type.
o['b'] = 3;
What does this error mean?
Here it is on the TypeScript playground - be sure to click Options and set noImplicitAny
(doesn't seem to remember options in shareable links).
The index signature simply maps a key type to a value type, and that's all. If you don't make that mapping correct, the value type can deviate from the actual runtime data type. To make typing more accurate, mark the indexed value as string or undefined. Doing so, TypeScript becomes aware that the properties you access might not exist: // etc...
Why index signature The idea of the index signatures is to type objects of unknown structure when you only know the key and value types. An index signature fits the case of the salary parameter: the function should accept salary objects of different structures — only that values to be numbers.
This behavior suggests that the index signature is meant to be generic in regards to keys. But you can use a union of string literals to describe the keys in a Record<Keys, Type>: The Record<Keys, Type> is meant to be specific in regards to keys. I recommend using the index signature to annotate generic objects, e.g. keys are string type.
I recommend using the index signature to annotate generic objects, e.g. keys are string type. But use Record<Keys, Type> to annotate specific objects when you know the keys in advance, e.g. a union of string literals 'prop1' | 'prop2' is used for keys.
The error is caused because the index signature is not explicitly defined.
You can declare an index signature
explicitly like so:
let ox : { [index:string] : number } = {};
ox['b'] = 3;
The reason o['a'] = 3;
doesn't error is because of rule 1 of bracket notation property access which is defined in the following rules from the spec:
- If index is a string literal or a numeric literal and object has an apparent property (section 3.11.1) with the name given by that literal (converted to its string representation in the case of a numeric literal), the property access is of the type of that property.
- Otherwise, if object has an apparent numeric index signature and index is of type Any, the Number primitive type, or an enum type, the property access is of the type of that index signature.
- Otherwise, if object has an apparent string index signature and index is of type Any, the String or Number primitive type, or an enum type, the property access is of the type of that index signature.
- Otherwise, if index is of type Any, the String or Number primitive type, or an enum type, the property access is of type Any.
- Otherwise, the property access is invalid and a compile-time error occurs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With