![](/img/trans.png)
[英]Why does TypeScript infer the 'never' type when reducing an Array with concat?
[英]Why does typescript give type `never` when excluding extended interface
我创建了一个剥离接口对象的函数。 但是,Typescript(版本3.2.2)现在声称该类型never
应该是具有属性child
的类型
interface Child extends Parent {
child: string
}
interface Parent {
parent: string
}
const a: Child = { child: "", parent: "" }
const b = removeParent(a);
function removeParent<T extends Parent>(obj: T) {
delete obj.parent;
return obj as Exclude<T, Parent>;
}
// b is now type never...
这确实有效:
function removeParent<T extends Parent>(obj: T) {
delete obj.parent;
type Without<T, K> = Pick<T, Exclude<keyof T, K>>;
return obj as Without<T, "parent">;
}
但是我想要一个通用的解决方案,不需要我写出要排除的类型。
我认为您不希望Exclude<T, Parent>
排除本质上是: type Exclude<T, U> = T extends U ? never : T
type Exclude<T, U> = T extends U ? never : T
结果,由于T在您的用法中扩展了Parent
,因此您的返回类型将never
不会返回。
我认为您真正想要的是: Pick<T, Exclude<keyof T, keyof Parent>>
所以您说的是“选择T在父级中不存在的所有属性”
function removeOneAndTwo<T extends Parent>(obj: T): Pick<T, Exclude<keyof T, keyof Parent>> {
delete obj.one;
delete obj.two;
return obj;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.