【发布时间】:2021-01-22 01:13:18
【问题描述】:
假设我有两个接口,X 和Y,它们共享一些字段,但也有独立的字段:
interface X {
abc: number;
foo: number;
bar: number;
}
interface Y {
abc: number;
foo: number;
baz: number;
}
现在我创建了这些类型的联合:
type Z = X | Y;
结果类型是either X or Y,这很好。现在我使用Omit 删除其中一个常用字段:
type limitedZ = Omit<Z, 'foo'>;
我希望limitedZ 具有以下形式:
{ abc: number, bar: number } | { abc: number, baz: number }
取而代之的是,独立的字段消失了,剩下的就是两者共享的abc 字段。这是为什么呢?
【问题讨论】:
-
很奇怪。如果我这样做
const x: limitedZ = {abc: 1, bar: 1, baz: 1};错误消息是:“Type '{ abc: number; bar: number; baz: number; }' is notassignable to type 'Pick”。这向我表明 Omit是根据Pick定义的,这反过来会导致联合类型出现问题,因为您不能声称limitedZ具有bar或baz财产。可能是因为它适用于{abc: number; foo: number;}的组合结果,它至少具有bar或baz之一,但也是可选的。 -
您可能可以在这里找到一些答案:stackoverflow.com/questions/57103834/…
-
“结果类型是 X 或 Y” - 这并不完全正确。它是“X 或 Y 或两者”(包括 OR),而 XOR 将是可区分的联合类型。至于为什么部分:
keyof,是Omit的一部分,只有returns all common properties。
标签: typescript types