Max Koretskyi
Max Koretskyi

Reputation: 105499

What's the need for `index` inside `[index: number]: string;`

I'm reading about Indexable Types here, and the following example is given:

interface StringArray {
    [index: number]: string;
}

let myArray: StringArray;
myArray = ["Bob", "Fred"];

let myStr: string = myArray[0];

I don't really understand why we need index here:

[index: number]: string;
 ^^^^^

It seems that I can use any name there and it will work, for example:

interface StringArray {
    [foo: number]: string;
}

let myArray: StringArray;
myArray = ["Bob", "Fred"];

let myStr: string = myArray[0];

I've also seen the following example:

ngOnChanges(changes: {[propName: string]: SimpleChange}): void {
    console.log('Changes', changes);
}

which as I understand uses some kind of inline indexable type declaration:

{[propName: string]: SimpleChange}

with propName instead of index.

Upvotes: 0

Views: 1000

Answers (1)

Fenton
Fenton

Reputation: 250922

In order to keep the syntax for type annotations consistent (they are based on type-theory annotations by the way), you need the type to appear after a name.

For example, the following is (stupid) but valid JavaScript:

var number = 5;

var arr = [number];

alert(arr[0]);

So imagine trying to parse a file and work out whether [number] is code or annotation... in the interface it may be pretty easy, but these annotations can appear practically anywhere. And then someone attempts to write an annotation, gets it wrong, and it becomes executable JavaScript.

So for consistency and sanity, type annotations always follow the same pattern...

{name}: {type}

You can read more about the link between TypeScript and Type Theory.

Upvotes: 2

Related Questions