user1482015
user1482015

Reputation:

TypeScript Interface Array Type error TS2411

I'm having difficulty trying to understand this:

There are two types of supported index types: string and number. It is possible to support both types of index, with the restriction that the type returned from the numeric index must be a subtype of the type returned from the string index.

While index signatures are a powerful way to describe the array and 'dictionary' pattern, they also enforce that all properties match their return type. In this example, the property does not match the more general index, and the type-checker gives an error:

interface Dictionary {
    [index: string]: string;
    length: number;    // error, the type of 'length' is not a subtype of the indexer
}

source:TypeScript Handbook's interface

I have tried 4 cases, but still cannot understand what is happening. Would anyone explain why only [index: string]: string; will has error TS2411? enter image description here

Another case:

another case

Upvotes: 10

Views: 5818

Answers (3)

lk_vc
lk_vc

Reputation: 1172

A workaround with TypeScript 2.4 is

interface Dictionary {
    [index: string]: string | number;
    length: number;
}

However, you may need to cast explicitly when using

let v = dict.key as string

Upvotes: 2

CoderPi
CoderPi

Reputation: 13211

It is possible to support both types of index, with the restriction that the type returned from the numeric index must be a subtype of the type returned from the string index.

Also there is no question mark, the answer is No. This Array wont work in any way:

interface Dictionary {
    [index: string]: string;
    length: number;  // error
}

because even this will work:

interface Dictionary {
    [index: string]: string;
}

var dic: Dictionary = {}
dic[1] = "123"

Note that we are indexing the string array with a number.

interface Dictionary { [index: string]: MYCLASS; } is meant to support you to define the value allowed, but not the type of the Index, sorry

What you are doing is not about interfaces but arrays: http://www.typescriptlang.org/Handbook#interfaces-array-types

Upvotes: 0

basarat
basarat

Reputation: 276199

if you have [index: string]: string; all properties must be a string. Hence:

interface Dictionary {
    [index: string]: string;
    length: number;    // error, length is not a string.
}

Upvotes: 6

Related Questions