I got an error in the following definition in typescript, may I know what is the problem?
interface Dictionary {
[index: string]: string;
length: number;
}
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.
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