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
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.
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.
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.
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.
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.
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