如何在typescript中定义自定义Map类型



我正在尝试使用Typescript泛型定义Map类型。我想要的是像这个一样的东西

EntityMap<U, V>, U can be only string or number

这就是我到目前为止所做的

export type EntityMapKey = string | number;
export type EntityMap<U, V> = { [K in EntityMapKey]: V};

但当我们使用它时,我们可以把任何像U一样的东西放在下面

interface Jobs {
list: EntityMap<Array, JobFile>
}

我想限制使用字符串数字以外的任何类型作为U,我们如何实现这一点?

我遗漏了什么吗?

EntityMap中的U没有使用,正确的实现应该是

export type EntityMapKey = string | number;
export type EntityMap<U extends EntityMapKey, V> = { [K in U]: V};
interface Jobs {
list: EntityMap<string, any>
}

最新更新