william007
william007

Reputation: 18535

The type returned from the numeric index must be a subtype of the type returned from the string index

In http://www.typescriptlang.org/Handbook#interfaces-array-types what does it means that "with the restriction that the type returned from the numeric index must be a subtype of the type returned from the string index."

Can someone give an example?

Upvotes: 2

Views: 126

Answers (1)

Seamus
Seamus

Reputation: 4819

Just for reference, there are two types of index signatures, string and numeric.

String index signature:

[index: string]: SomeType

This says that when I access a property of this object by a string index, the property will have the type SomeType.

Numeric index signature:

[index: number]: SomeOtherType

This says that when I access a property of this object by a numeric index, the property will have the type SomeOtherType.

To be clear, accessing a property by string index is like this:

a["something"]

And by numeric index:

a[123]

You can define both a string index signature and a numeric index signature, but the type for the numeric index must either be the same as the string index, or it must be a subclass of the type returned by the string index.

So, this is OK:

interface SomeInterface {
    [index: string]: Fruit;
    [index: number]: Fruit;
}

Because both index signatures have the same type Fruit. But you can also do this:

interface SomeInterface {
    [index: string]: Fruit;
    [index: number]: Apple;
}

As long as Apple is a subclass of Fruit.

Upvotes: 3

Related Questions