首页 > 解决方案 > TypeScript 中的字典类型

问题描述

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

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

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

interface MyInterface {
    data: Dict<Item>;
}

标签: typescripttypescript-typings

解决方案


我们可以尝试使用名为的内置打字稿高级类型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" }
    }
};

推荐阅读