Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 307
Aviel Fedida Avatar asked Oct 31 '22 02:10

Aviel Fedida


1 Answers

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.

like image 150
basarat Avatar answered Nov 12 '22 19:11

basarat