Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are object index signatures are equivalent to array types?

Tags:

typescript

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?

like image 275
Stuart Rackham Avatar asked Nov 24 '12 04:11

Stuart Rackham


People also ask

What is an index signature?

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.

Which type string has no matching index signature?

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 .

Is incompatible with index signature?

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.

How do I create a index signature in TypeScript?

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.


1 Answers

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).

like image 163
Ryan Cavanaugh Avatar answered Nov 15 '22 05:11

Ryan Cavanaugh