为Map创建接口或类型



我想要一个JavaScriptMap的单一类型或接口。

给定基本代码:

const things = new Map();

我目前创建了一个类型和一个接口来显式键入things变量和Map构造函数调用。

type Things = Map<string, ThingValue>;
interface ThingValue {
label: string;
count: number;
}

const things: Things = new Map<string, ThingValue>();

我希望有一个单一的类型或接口,这样我就不必重复<string, ThingValue>

这可能吗?或者,键入JavaScriptMaps的最佳实践是什么?

您有三个选项可以在没有冗余的情况下正确键入地图:

type Things = Map<string, ThingValue>;
interface ThingValue {
label: string;
count: number;
}
const things1: Things = new Map();
const things2 = new Map<string, ThingValue>();
// not recommended
const mapFactory = () => new Map<string, ThingValue>();
const things3 = mapFactory();

所有这些都将产生相同的类型,并包含传达该类型所需的最少信息。

最新更新