【发布时间】:2021-02-03 10:28:31
【问题描述】:
我想编写一个通用的创建方法,该方法可以生成在地图中输入的不同对象。问题是打字稿将所有接口混合在一起,而不是只在接口映射中选择一个:
interface A {
a: string;
}
interface B {
b: string;
}
interface ABMap {
a: A;
b: B;
}
function create<ID extends keyof ABMap>(id: ID): ABMap[ID] { // this is now combined A & B instead of A | B
if (id === 'a') {
return {a: 'a'}; // error a is missing b key
} else if (id === 'b') {
return {b: 'b'};
}
}
【问题讨论】:
-
问题似乎是if语句没有缩小
id的类型,它仍然在分支中有ID extends "a" | "b"类型。 -
我目前已使用此帮助程序
type ValueOf<T> = T[keyof T];修复了错误,然后返回ValueOf<ABMap>。但也许有更好的解决方案。 -
这里是一个issue mentioning the problem,虽然
ID & 'a'类型可能也没有帮助,但需要将其缩小为'a'。
标签: typescript generics interface typescript-generics