Chic
Chic

Reputation: 10509

How to create generic Map interface in TypeScript

I would like to create a Map interface in TypeScript but I cannot seem to figure out how to constrain the property accessor to please the compiler

Desired Interface

export interface IMap<I extends string | number, T> {
  [property: I]: T;
}

Error:

An index signature type must be 'string' or 'number'

Upvotes: 24

Views: 58903

Answers (1)

Seamus
Seamus

Reputation: 4819

You are allowed to define both a string and numeric index signature.

From the spec:

An object type can contain at most one string index signature and one numeric index signature.

So you can do this:

interface IMap<T> {
    [index: string]: T;
    [index: number]: T;
} 

Is that what you were after?

Also, when you define only a string index signature:

Specifically, in a type with a string index signature of type T, all properties and numeric index signatures must have types that are assignable to T.

And so:

class Foo {
    [index: string]: number;
}

let f = new Foo();

f[1] = 1; //OK

f[6] = "hi"; //ERROR: Type 'string' is not assignable to type 'number'

Upvotes: 36

Related Questions