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

172 Views Asked by At

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.

1

There are 1 best solutions below

0
On BEST ANSWER

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.