roger
roger

Reputation: 9943

How to declare a Map type in typescript?

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

Upvotes: 34

Views: 59653

Answers (2)

windmaomao
windmaomao

Reputation: 7680

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.

Upvotes: 8

David Sherret
David Sherret

Reputation: 106900

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.

Upvotes: 57

Related Questions