6

在我的应用程序的几个地方,我声明了一个字典类型,例如:

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

TypeScript 中是否有任何内置的字典/地图简写,以获得类似于:

interface MyInterface {
    data: Dict<Item>;
}
4

2 回答 2

11

我们可以尝试使用名为的内置打字稿高级类型Record<K, T>

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

把所有东西放在一起

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

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

const obj: MyInterface = {
    data: {
        "123": { id: "123", name: "something" }
    }
};
于 2019-05-29T05:12:45.783 回答
1

另一种解决方案:

export interface Dict<T> {
    [key: string]: T;
}

这是在 orbit.jsDict中使用的类型。

于 2021-04-17T04:41:16.273 回答