Reputation: 152304
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>;
}
Upvotes: 19
Views: 43237
Reputation: 36217
We can try with built-in typescript advanced type called Record<K, T>
. Here is official documentation https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type
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" }
}
};
Upvotes: 40