我有一个简单的例子,就是从另一个已经省略的类型中省略属性:
type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;
interface A {
x: string;
y: number;
}
interface B extends A {
z: Date;
w: boolean;
}
type OmitA<T extends A> = Omit<T, 'x'>;
type OmitB<T extends B> = Omit<OmitA<T>, 'z'>;
如预期的那样,OmitA 类型只有属性“y”。但是 OmitB 类型抛出错误:
Type '"z"' does not satisfy the constraint 'Exclude<keyof T, "x">'. ts(2344)
这是一个错误还是这段代码有问题?
更新 1
如果我将 OmitB 类型更改为:
type OmitB<T extends B> = Omit<OmitA<T & B>, 'z'>;
我觉得没必要。
最佳答案
这是您定义 Omit
方式的限制, K
必须是 keyof T
.但是因为 T
是一个未解析的类型参数 typescript 无法确定是否 Omit<T, 'x'>
将真正包含 z
(更像是它不打扰)。有办法解决这个问题,但最简单的解决方案是使用 Omit
的定义。这将很快添加到不需要 K
的 typescript 3.5 ( PR) 中至 extend keyof T
type Omit<T, K> = Pick<T, Exclude<keyof T, K>>; // no constraint as in the new Omit in 3.5
interface A {
x: string;
y: number;
}
interface B extends A {
z: Date;
w: boolean;
}
type OmitA<T extends A> = Omit<T, 'x'>;
type OmitB<T extends B> = Omit<OmitA<T>, 'z'>; // works fine now
关于typescript - 为什么我不能从已经省略的类型中省略属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56161918/