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
export interface IMap<I extends string | number, T> {
[property: I]: T;
}
An index signature type must be 'string' or 'number'
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.
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.
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.
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.
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With