Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create generic Map interface in TypeScript

Tags:

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'

like image 799
Chic Avatar asked Jan 08 '16 21:01

Chic


People also ask

How do I create a Map Map in TypeScript?

Creating a MapUse Map type and new keyword to create a map in TypeScript. let myMap = new Map<string, number>(); To create a Map with initial key-value pairs, pass the key-value pairs as an array to the Map constructor.

How do I create an interface in TypeScript?

Example: Interface and Objectsinterface IPerson { firstName:string, lastName:string, sayHi: ()=>string } var customer:IPerson = { firstName:"Tom", lastName:"Hanks", sayHi: ():string =>{return "Hi there"} } console. log("Customer Object ") console. log(customer. firstName) console.

What is Map interface in TypeScript?

TypeScript map is a new data structure added in ES6 version of JavaScript. It allows us to store data in a key-value pair and remembers the original insertion order of the keys similar to other programming languages. In TypeScript map, we can use any value either as a key or as a value.

How do I iterate through a Map in TypeScript?

Use the forEach() method to iterate over a Map in TypeScript. The forEach method takes a function that gets invoked for each key/value pair in the Map . The function gets passed the value, key and the Map object on each iteration.


1 Answers

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'
like image 170
Seamus Avatar answered Sep 20 '22 22:09

Seamus