所以我有这个标记的联合类型:
type A = {
type: 'a';
attr1: number;
};
type B = {
type: 'b';
attr1: string;
attr2: boolean;
};
type C = {
type: 'c';
attr5: object;
attr6: boolean;
};
type U = A | B | C;
我想要拥有该类型的部分对象。所以我尝试使用部分:
type PartialU = Partial<U>;
但这会带来问题,因为该type
属性也被标记为可选:
type PartialU = Partial<U>;
// ^?
// {
// type?: 'a';
// attr1?: number;
// } | {
// type?: 'b';
// attr1?: string;
// attr2?: boolean;
// } | {
// type?: 'c';
// attr5?: object;
// attr6?: boolean;
// }
这会导致标记的联合不再真正被标记,因为值并不是每个替代项所独有的,因为它们中的任何一个都可能是未定义的,从而违背了联合的目的。
我更喜欢这样的类型:
{
type: 'a';
attr1?: number;
} | {
type: 'b';
attr1?: string;
attr2?: boolean;
} | {
type: 'c';
attr5?: object;
attr6?: boolean;
}
有没有一种明显的方法可以实现这一目标?
Partial<U>
在和之间建立交集怎么样Pick<U, 'type'>
?您可以创建一个实用程序类型,例如:
并将其用于您的情况:
这将确保这
type
不是对象的一部分,而是对象的其余部分。