[英]why typescript behaves differently when using the type directly vs using generics with extends?
我不明白为什么代码在使用 generics 时表现不同。
该主题基于How to create a relation between parameters of a function? 的答案。
interface Data {
a: number,
b: { x: number, y: number}
}
type GetKeyValueTuples<T> = { [Key in keyof T]: [Key, T[Key]] }[keyof T];
function getChangedDataByProperty<T extends Data>(
...[data, changedProp, newPropValue]: [T, ...GetKeyValueTuples<T>]
) {
if (changedProp === "b") {
changedProp
return {
...data,
b: {
// why this has number, a, b types?
x: newPropValue.x,
y: newPropValue.y,
}
}
} else {
return {
...data,
x: newPropValue
}
}
}
// why this behaves differently than the abvove function?
function getChangedDataByProperty2(
...[data, changedProp, newPropValue]: [Data, ...GetKeyValueTuples<Data>]
) {
if (changedProp === "b") {
changedProp
return {
...data,
b: {
x: newPropValue.x,
y: newPropValue.y,
}
}
} else {
return {
...data,
x: newPropValue
}
}
}
getChangedDataByProperty2()
函数的rest 参数是可区分的联合类型,自 TypeScript 4.6 以来,我们已经能够将此类可区分的联合解构为单独的参数,以获得您所看到的缩小行为,其中对可区分的changedProp
的检查缩小了newPropValue
的类型。
另一方面, getChangedDataByProperty()
的 rest 参数是一个通用类型,它最终被限制为相同的可区分联合类型。 无论出于何种原因,TypeScript 都不认为泛型类型是可区分联合的可接受的判别式。 在microsoft/TypeScript#50652上有一个关于此的问题,但它目前被标记为“需要调查”,所以没有官方的说法来说明这是一个错误、设计限制,还是可以解释为一个功能请求。 它也在积压中,这意味着这样的官方消息可能不会出现。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.