如何在打字稿中定义自定义地图类型?

时间:2020-05-03 13:25:10

标签: angularjs typescript typescript-generics

我正在尝试使用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>
}

我想限制使用 string number 以外的任何其他类型作为U,我们如何实现呢?

我错过了什么吗?

1 个答案:

答案 0 :(得分:0)

未使用EntityMap中的U,应使用正确的实现

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