问题描述
type Union = { a: "foo",b: string,c: number } | {a: "bar",b: boolean }
我需要派生一个包含所有潜在属性的类型,分配的类型可以在 Union
的任何成员上找到,即使仅在某些成员上定义 - 在我的示例中:
type CollapsedUnion = {
a: "foo" | "bar",b: string | boolean,c: number | undefined
}
我怎样才能制作一个派生出这种折叠联合的泛型?
我需要一个支持任何大小联合的泛型。
可以实现类似的行为 as a byproduct by using native Omit
utility,但不幸的是,它遗漏了每个联合成员上不存在的属性(不将它们计入 undefined
或通过 ?
) .
解决方法
我找到了一种两种方式!
编辑:这是一个具有两个独立类型参数的解决方案。有关具有单个联合类型参数的解决方案,请参见下方。
// The source types
type A = { a: "foo",b: string,c: number }
type B = { a: "bar",b: boolean }
// This utility lets T be indexed by any (string) key
type Indexify<T> = T & { [str: string]: undefined; }
// Where the magic happens ✨
type AllFields<T,R> = { [K in keyof (T & R) & string]: Indexify<T | R>[K] }
type Result = AllFields<A,B>
/**
* ?
* type Result = {
* a: "foo" | "bar";
* b: string | boolean;
* c: number | undefined;
* }
*/
工作原理
AllFields
是映射类型。映射类型的“key”部分
[K in keyof (T & R) & string]
表示 K
扩展联合 T & R
的键,这意味着它将是 T
或 R
中的所有键的联合。这是第一步。它确保我们使用所有必需的键创建一个对象。
& string
是必需的,因为它指定 K
也必须是字符串。无论如何,情况几乎总是如此,因为 JS 中的所有对象键都是字符串(偶数)——除了符号,但无论如何这些都是不同的鱼。
类型表达式
Indexify<T | R>
返回 T
和 R
的联合类型,但添加了字符串索引。这意味着如果我们尝试通过 K
索引它,即使在K
不存在于 T
或 R
之一中。
最后
Indexify<T | R>[K]
表示我们通过 K
索引这个 union-with-undefineds-for-string-indexes。其中,如果 K
是 T
、R
或两者的键,将导致该键的值类型。
否则,它将回退到 [string]: undefined
索引并导致值为 undefined。
编辑:单个通用参数的解决方案
您指定您实际上并不希望这适用于两个类型参数,而是使用现有联合类型,无论联合中有多少成员。
我付出了鲜血、汗水和泪水,但我已经明白了。
// Magic as far as I'm concerned.
// Taken from https://stackoverflow.com/a/50375286/3229534
type UnionToIntersection<U> =
(U extends any ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never
// This utility lets T be indexed by any key
type Indexify<T> = T & { [str: string]: undefined; }
// To make a type where all values are undefined,so that in AllUnionKeys<T>
// TS doesn't remove the keys whose values are incompatible,e.g. string & number
type UndefinedVals<T> = { [K in keyof T]: undefined }
// This returns a union of all keys present across all members of the union T
type AllUnionKeys<T> = keyof UnionToIntersection<UndefinedVals<T>>
// Where the (rest of the) magic happens ✨
type AllFields<T> = { [K in AllUnionKeys<T> & string]: Indexify<T>[K] }
// The source types
type A = { a: "foo",b: boolean; }
type Union = A | B
type Result = AllFields<Union>
/**
* ?
* type Result = {
* a: "foo" | "bar";
* b: string | boolean;
* c: number | undefined;
* }
*/
我从@jcalz 的精彩回答中得到了 UnionToIntersection
。我试图理解它,但不能。无论如何,我们可以将其视为将联合类型转换为交集类型的魔术盒。这就是我们获得想要的结果所需的全部。
这是可行的;下面介绍了一种可能的解决方案。如果有可能以更简单的方式实现它,我会很感兴趣。我添加了注释来引导您完成代码。
// an axiliary type -- we need to postpone creating a proper union,as a tuple type can be traversed recursively
// I added additional branch to make the task a bit harder / to make sure it works in a more generic case
type ProtoUnion = [{ a: "foo",c: number },{a: "bar",b: boolean },{ c: string }]
// an axiliary type to recover proper Union
type CollapseToUnion<T extends Record<string,any>[],Acc = {}> = // starting with a tuple of records and accumulator
T extends [infer H,...infer Rest] ? // traverse
Rest extends Record<string,any>[] ? // if still a record present
CollapseToUnion<Rest,(H | Acc)> : // recursive call: collapse as union
// in other cases return accumulator
Acc :
Acc
// union recovered
type Union = CollapseToUnion<ProtoUnion>
// this type is empty,so starting with union is _impossible_ to recover all needed keys in a generic way
type UnionKeys = keyof Union
// this type achieves what you are asking for but only for 2 types
type MergeAsValuesUnion<A,B> = { [K in (keyof A | keyof B)]:
K extends keyof A ?
K extends keyof B ? A[K] | B[K] :
A[K] | undefined :
K extends keyof B ? B[K] | undefined :
never
}
type OriginalUnionIntersected = MergeAsValuesUnion<ProtoUnion[0],ProtoUnion[1]>
/*
type OriginalUnionIntersected = {
a: "foo" | "bar";
b: string | boolean;
c: number | undefined;
}
*/
// this is works exactly the same as CollapseToUnion,but instead of reducing with |
// it uses MergeAsValuesUnion to reduce
type CollapseToIntersetion<T extends Record<string,Acc = {}> = T extends [infer H,...infer Rest] ?
Rest extends Record<string,any>[] ?
CollapseToIntersetion<Rest,MergeAsValuesUnion<H,Acc>>
: Acc : Acc
const i: CollapseToIntersetion<ProtoUnion> = {
a: 'bar',// "bar" | "foo" | undefined
b: true,// string | boolean | undefined
c: undefined // string | number | undefined
}
编辑:
CollapseToIntersetion
有点不对劲。以 {}
作为默认累加器开始会导致在值类型中有 | undefined
。
// this is works exactly the same as CollapseToUnion,// but instead of reducing with | -- it uses MergeAsValuesUnion to reduce;
// Acc = T[0] since Acc = {} would result in all values types unioned with undefined
type CollapseToIntersetion<T extends Record<string,Acc = T[0]> = T extends [infer H,Acc>>
: Acc : Acc