Reputation: 8731
As said in the Handbook, you can declare a custom array interface with string or number index:
interface StringArray {
[index: number]: string;
}
So I made this:
interface EventRegistrations {
[index:string]:ListenerEntry[];
}
problem is simple: how can I initialize such a thing?
Here is what I tried and the error message provided (using PhpStorm 2016.1 with tsc 1.8.7):
foo:EventRegistrations = [];
Type 'undefined[]' is not assignable to type 'EventRegistrations'
foo:EventRegistrations = [[]];
Type 'undefined[][]' is not assignable to type 'EventRegistrations'
foo:EventRegistrations = [index:string]:ListenerEntry[];
Syntax error (expected , where first : is)
foo:EventRegistrations = [string]:ListenerEntry[];
Syntax error (expected ; where : is)
foo:EventRegistrations = new EventRegistrations();
Syntax error (cannot find name 'EventRegistrations')
Upvotes: 0
Views: 2393
Reputation: 42390
In this case, you are not actually defining an array []
, you are defining a dictionary {}
, since string indexers are used for dictionary style lookup.
In the following example, you will see that the object is declared using {}
rather than []
, because in JavaScript, all objects are dictionaries (even arrays!) Arrays just have special semantics and a length
property that allows them to behave like arrays (numerically indexed)
interface ListenerEntry {
foo: string;
bar: string;
}
interface EventRegistrations {
[index:string]:ListenerEntry[];
}
var x: EventRegistrations = {};
x["one"][0].foo = "Hello";
x["two"][1].bar = "World";
Upvotes: 1