Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dictionary type in TypeScript

In a few places in my application, I'm declaring a dictionary types, like:

interface MyInterface {
    data: { [key: string]: Item };
}

Is there in TypeScript any built-in shorthand for the dictionaries/maps, to get something similar to:

interface MyInterface {
    data: Dict<Item>;
}
like image 369
hsz Avatar asked May 29 '19 05:05

hsz


People also ask

How do I create a dictionary in TypeScript?

We can create a dictionary with the initial data as key-value pairs: let dictionaryViaLiteral = { 'firstName': 'Gapur', 'lastName': 'Kassym', 'country': 'Kazakhstan' }; We created the dictionaryViaLiteral dictionary with the key and value as string types.

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 define a key value pair in TypeScript?

Use an index signature to define a key-value pair in TypeScript, e.g. const employee: { [key: string]: string | number } = {} . An index signature is used when we don't know all the names of a type's keys ahead of time, but we know the shape of their values.


1 Answers

We can try with built-in typescript advanced type called Record<K, T>

interface MyInterface {
    data: Record<string, Item>;
}

Put everything together here

interface Item {
    id: string;
    name: string;
}

interface MyInterface {
    data: Record<string, Item>;
}

const obj: MyInterface = {
    data: {
        "123": { id: "123", name: "something" }
    }
};
like image 113
Raja Jaganathan Avatar answered Sep 28 '22 08:09

Raja Jaganathan