How do I declare a TypeScript Map type?

How do I declare a TypeScript Map type?

I’m creating a class in TypeScript with a property that is an ES6 (ECMAScript 2016) Map like this:

 codeclass Item {
  configs: ????;
  constructor () {
    this.configs = new Map();
  }

How should I declare the type of configs using the TypeScript map type?

Hey to handle Specific Key-Value Types, You can explicitly define the key-value pair types for your map by specifying the types in the Map constructor.

For example, if the map stores string keys and number values, the declaration would look like this:

class Item {
  configs: Map<string, number>;
  constructor() {
    this.configs = new Map();
  }
}

In this solution, Map<string, number> is the typescript map type for storing a string as the key and a number as the value.

You can try this. This worked for me :slight_smile:

Using Map with Custom Object Types: If you want the Map to store complex types, such as objects, you can define the types for the keys and values as needed. For instance:

class Item {
  configs: Map<string, { id: number, name: string }>;
  constructor() {
    this.configs = new Map();
  }
}

In this case, the typescript map type is a Map<string, { id: number, name: string }> where the map’s keys are strings and values are objects containing an id and name.

Hey

TypeScript can infer the types of keys and values based on how you initialize the map. You can skip explicitly specifying the types if you initialize the map with values:

class Item {
  configs: Map<string, boolean>;
  constructor() {
    this.configs = new Map([
      ['isActive', true],
      ['isVerified', false],
    ]);
  }
}

Here, the typescript map type will be inferred as Map<string, boolean> based on the initial values. TypeScript automatically deduces that the keys are strings and the values are booleans.