Section 3.5.4 of the spec states: "An array type of the form ElementType[] is equivalent to an object type with the index signature [index: number]: ElementType" but this does not appear to be the case e.g.
var a: {[index: number]: string;};
var b: string[];
a = ['1','2']; // ERROR: Cannot convert 'string[]' to '{ [index: number]: string; }'
b = ['1','2']; // OK
What am I missing here?
Index signature is used to represent the type of object/dictionary when the values of the object are of consistent types. Syntax: { [key: KeyType] : ValueType } Assume that we have a theme object which allows us to configure the color properties that can be used across the application.
The error "No index signature with a parameter of type 'string' was found on type" occurs when we use a value of type string to index an object with specific keys. To solve the error, type the string as one of the object's keys using keyof typeof obj .
The error "Property is incompatible with index signature" occurs when a property is not compatible with the specified type of the index signature. To solve the error, change the type of the property or use a union to update the type in the index signature.
The index signature consists of the index name and its type in square brackets, followed by a colon and the value type: { [indexName: KeyType]: ValueType } . KeyType can be a string , number , or symbol , while ValueType can be any type.
Yep, this is a known bug in the compiler. It'll be fixed in a future release. The best workaround is a cast (on either side of the assignment - a = <string[]>['1', '2']
probably looks slightly less weird).
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