Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a static Map in typescript?

Tags:

typescript

I would like to create a static Map which will contain key value pairs which are of both strings. This key value pair is never going to change.

Something like follows:

static KEY_VALUE_PAIR: Map<string, string>: {
 'space' : 'jump',
 'enter' : 'hit'
}

When I do this, I get an error saying Type '{ 'space': string; }' is not assignable to type 'Map<string, string>'. Am I doing something wrong here?

If I remove the return type Map<string, string>, it's a plain object and it works fine.

like image 601
Tums Avatar asked Sep 20 '25 21:09

Tums


1 Answers

A static map in Typescript can be created and initialized inline by creating a new Map object like this:

const KEY_VALUE_PAIR = new Map<string, string>([
  ['space','jump'],
  ['enter','hit']
]);
like image 150
Sumit Avatar answered Sep 22 '25 11:09

Sumit