Aviel Fedida
Aviel Fedida

Reputation: 4102

What is the use case for supporting "both types of index" (numeric and string) in TypeScript?

I'v start using typescript and came into the following statement(taken from Interfaces#array-types):

It is possible to support both types of index, with the restriction that the type returned from the numeric index must be a subtype of the type returned from the string index.

I can think of few ways to have both numeric and string indexer types but none make sense with above quote, I'd be glad to have some code examples demonstrates what they meant.

Upvotes: 5

Views: 163

Answers (1)

basarat
basarat

Reputation: 275849

I'd be glad to have some code examples demonstrates what they meant.

The following is allowed :

interface A{
}
interface B{
    foo: number;
}

interface Something {   
    [index: string]: A;
    [index: number]: B;     
}

But this is not:

interface A{
    foo: number;
}
interface B{    
}

interface Something {   
    [index: string]: A;
    [index: number]: B;     
}

To Quote : "type returned from the numeric index must be a subtype of the type returned from the string index" So in our example B must be subtype of A.

Upvotes: 2

Related Questions