william007
william007

Reputation: 18525

TypeScript interface definition type error

I got an error in the following definition in typescript, may I know what is the problem?

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

Upvotes: 1

Views: 595

Answers (2)

JayChase
JayChase

Reputation: 11525

Please see the TypeScript documentation on array types. All properties must have the same return type so you can't declare length with a return type number on the interface.

To get the length of the array you could cast back to a generic array type:

    (<Array<any>>yourArray).length

Upvotes: 0

Seamus
Seamus

Reputation: 4819

In your Dictionary interface,

[index: string]: string;

is called a string index signature, and tells the compiler all properties of a Dictionary must be of type string. You would commonly use an index signature to avoid having an array of mixed types.

So then doing this is OK:

let d: Dictionary;
d["foo"] = "bar";

But this will give a compiler error:

let d: Dictionary;
d["foo"] = 1000;

You can define properties for Dictionary, as long as every property you define is of type string. For example, this is OK:

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

And will allow you to do this:

let d: Dictionary;
d.foo = "bar";

But in your case, you tried to define a property called length as a number after you already told the compiler that all properties would be of type string. That's why you got a compiler error.

Upvotes: 1

Related Questions