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>;
}
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.
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.
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.
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" }
}
};
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