Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare a Map type in typescript?

Tags:

I want to declare a type like this:

interface DependData {[key: string]: string};

but with error like this:

Statements are not allowed in ambient contexts
like image 288
roger Avatar asked Jul 20 '16 17:07

roger


People also ask

How do you define a type Map in TypeScript?

We use the Map as a data structure to store key-value entries. It is also known as a dictionary. In TypeScript, we can easily create a Map using the new keyword and provide the data types for keys and values.

How do you get a Keys Map in TypeScript?

We use the get() method of a map in TypeScript to get the value for a key in a map. A map is a key-value pair data structure.

How do I iterate 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.


2 Answers

The error message you are describing occurs in a declaration file.

To make this work, you need remove the semi-colon at the end of your interface declaration:

interface DependData {
    [key: string]: string;
}

The extra semi-colon is causing an empty statement to be parsed in addition to the interface declaration, thus giving that error message.

like image 96
David Sherret Avatar answered Oct 25 '22 20:10

David Sherret


I'm not good at typescript, and when I dig into our codebase, i found the following approach is also valid, and can be more robust, because otherwise you won't be able to use non-string as keys.

export enum SORT_TYPES {
  DISPLAY_NAME_ASC = 'Patient: A-Z',
  DISPLAY_NAME_DESC = 'Patient: Z-A',
}

export const SORT_ORDERS: Map<SORT_TYPES, String[]> = new Map([
  [SORT_TYPES.DISPLAY_NAME_ASC, ['display_name', 'ASC']],
  [SORT_TYPES.DISPLAY_NAME_DESC, ['display_name', 'DESC']],
])

So here a Map type is used, and the key type becomes SORT_TYPES instead of a string.

like image 40
windmaomao Avatar answered Oct 25 '22 20:10

windmaomao