0

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

1 Answer 1

1

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";
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.