我需要将联合对象类型(可能具有嵌套的联合)转换为 可选值的深交集 类型。本质上,所有可能的字段都将相交,并且只有在并集的一侧存在时才是可选字段-并对所有嵌套对象执行此操作。
注意:这不是简单的相交联合
内嵌其他评论:
type DateOnly = string;
type DayOfWeek = string;
type DayOfMonth = string;
// Input Type:
type DateIntervals_Union = {
kind: 'weekly';
weekly: {
startDayOfWeek: DayOfWeek;
endDayOfWeek: DayOfWeek;
startDate: DateOnly;
endDate?: DateOnly;
};
} | {
kind: 'monthly';
monthly: {
startDayOfMonth: DayOfMonth;
endDayOfMonth: DayOfMonth;
startDate: DateOnly;
endDate?: DateOnly;
};
} | {
kind: 'dates';
dates: {
dateRanges: {
startDate: DateOnly;
endDate: DateOnly;
}[];
};
};
// Expected Type:
type DateIntervals_Optionals = {
// This becomes a union of it's possible values
kind: 'weekly' | 'monthly' | 'dates';
// This becomes a union between the object and undefined
weekly?: {
// These are unchanged
startDayOfWeek: DayOfWeek;
endDayOfWeek: DayOfWeek;
startDate: DateOnly;
endDate?: DateOnly;
};
monthly?: {
startDayOfMonth: DayOfMonth;
endDayOfMonth: DayOfMonth;
startDate: DateOnly;
endDate?: DateOnly;
};
dates?: {
dateRanges: {
startDate: DateOnly;
endDate: DateOnly;
}[];
};
};
// Input Type:
type Schedule_Union = {
kind: 'once';
date: DateOnly;
} | {
kind: 'recurring';
schedule: DateIntervals_Union;
};
// Expected Type:
type Schedule_Optionals = {
// Union of possible values
kind: 'once' | 'recurring';
// Union of possible values: date | undefined
date?: DateOnly;
// Union of possible values: schedule | undefined
// But the same union => optional type conversion is applied in this nested object
schedule?: {
kind: 'weekly' | 'monthly' | 'dates';
weekly?: {
startDayOfWeek: DayOfWeek;
endDayOfWeek: DayOfWeek;
startDate: DateOnly;
endDate?: DateOnly;
};
monthly?: {
startDayOfMonth: DayOfMonth;
endDayOfMonth: DayOfMonth;
startDate: DateOnly;
endDate?: DateOnly;
};
dates?: {
dateRanges: {
startDate: DateOnly;
endDate: DateOnly;
}[];
};
}
};
// Simple UnionToIntersection does not work:
type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never;
type Schedule_UnionToIntersection = UnionToIntersection<Schedule_Union>;
type Schedule_UnionToIntersection_Actual = {
kind: 'once';
date: DateOnly;
} & {
kind: 'recurring';
schedule: DateIntervals_Union;
};
// Partial<UnionToIntersection> does not work:
type PartialUnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends ((k: infer I) => void) ? Partial<I> : never;
type Schedule_PartialUnionToIntersection = PartialUnionToIntersection<Schedule_Union>;
type Schedule_PartialUnionToIntersection_Actual = {
kind?: undefined;
date?: string | undefined;
schedule?: {
kind: 'weekly';
weekly: {
startDayOfWeek: string;
endDayOfWeek: string;
startDate: string;
endDate?: string | undefined;
};
// Not nested
} | {
kind: 'monthly';
// Um.. no, that's not right - where did that even come from?
weekly: {
// Bonus points if you can figure out how to make vscode show the full type information
//...;
};
} | {
//...;
} | undefined;
};
这为提取数据提供了更直接的模式:
// BAD: This is not nice when needing to extract a single value
const funWith_unions = (dateIntervals_union: DateIntervals_Union) => {
// If won't be null eventually :P
let startDate: string = null as unknown as string;
if (dateIntervals_union.kind === 'dates') {
startDate = dateIntervals_union.dates.dateRanges[0]?.startDate;
} else if (dateIntervals_union.kind === 'monthly') {
startDate = dateIntervals_union.monthly.startDate;
} else {
startDate = dateIntervals_union.weekly.startDate;
}
if (!startDate) { throw new Error('No start date'); }
}
// GOOD: Quick, simple, and safe
const funWith_wide = (dateIntervals_wide: Widen<DateIntervals_Union>) => {
// All possible cases handled in a single statement
const startDate = dateIntervals_wide.dates?.dateRanges[0].startDate
?? dateIntervals_wide.monthly?.startDate
?? dateIntervals_wide.weekly?.startDate
?? (() => { throw new Error('No start date'); })()
}
// The above uses the excellent code from @jcalz (the accepted answer):
type AllKeys<T> = T extends any ? keyof T : never;
type OptionalKeys<T> = T extends any ?
{ [K in keyof T]-?: {} extends Pick<T, K> ? K : never }[keyof T] : never;
type Idx<T, K extends PropertyKey, D = never> =
T extends any ? K extends keyof T ? T[K] : D : never;
type PartialKeys<T, K extends keyof T> =
Omit<T, K> & Partial<Pick<T, K>> extends infer O ? { [P in keyof O]: O[P] } : never;
type Widen<T> =
[T] extends [Array<infer E>] ? { [K in keyof T]: Widen<T[K]> } :
[T] extends [object] ? PartialKeys<
{ [K in AllKeys<T>]: Widen<Idx<T, K>> },
Exclude<AllKeys<T>, keyof T> | OptionalKeys<T>
> :
T;
答案 0 :(得分:3)
好吧,我要称呼您正在做的事情Widen
,因为它的名字不会太长。如果我理解正确,那么思考您正在做的事情的一种方法是采用对象类型的并集,并假设如果该联合成员的声明的类型中不存在某个属性,它实际上不存在(特别是类型为never
或undefined
的可选属性)。
因此,可以将类似{foo: string, baz: true} | {bar: number, baz: false}
的类型视为{foo: string, bar?: never, baz: true} | {foo?: never, bar: number, baz: false}
。然后,您想要做的就是按照通常的规则将它们合并到一个单一的类型中,在该规则中,您将每个属性的并集合并,并且每个属性都是可选的,当且仅当它在至少一个工会会员,例如:{foo?: string, bar?: number, baz: boolean}
。
然后通过对象类型递归进行操作。
这是我尝试编写此代码的一种方法。我会提到我在做什么,但不一定 关于其工作原理的细节,否则可能是十页文字:
首先让我们定义一个类型AllKeys<T>
,该类型将keyof
分布在各个联合中,因此AllKeys<{a: string} | {b: number}>
是"a" | "b"
:
type AllKeys<T> = T extends any ? keyof T : never;
然后,我们写一个类型OptionalKeys<T>
仅标识该类型中的可选键(并且它也分布在联合中),因此OptionalKeys<{a?: string, b: number} | {c: boolean, d?: null}>
应该为"a" | "d"
:
type OptionalKeys<T> = T extends any ?
{ [K in keyof T]-?: {} extends Pick<T, K> ? K : never }[keyof T] : never;
然后让我们写一个类型Idx<T, K, D>
来查找类型K
的{{1}}属性,除了它分布在联合中,如果没有这样的属性,它将返回默认类型{{ 1}}。因此,T
应该是D
:
Idx<{a: string} | {b: number}, "a", 100>
还有一个名为string | 100
的类型,它类似于type Idx<T, K extends PropertyKey, D = never> =
T extends any ? K extends keyof T ? T[K] : D : never;
,但它只作用于键PartialKeys<T, K>
上,而其他Partial<T>
中的键则单独保留。因此K
与T
相同,而Partial<T, keyof T>
与Partial<T>
相同:
Partial<T, never>
最后 这是T
:
type PartialKeys<T, K extends keyof T> =
Omit<T, K> & Partial<Pick<T, K>> extends infer O ? { [P in keyof O]: O[P] } : never;
我们使用特殊情况的数组,因为在数组上的映射是treated specially by the compiler,否则我们仅在对象类型上映射而不是在基元上映射(您不希望看到在Widen<T>
上映射时会发生什么,例如)。但是总的计划是:获取type Widen<T> =
[T] extends [Array<infer E>] ? { [K in keyof T]: Widen<T[K]> } :
[T] extends [object] ? PartialKeys<
{ [K in AllKeys<T>]: Widen<Idx<T, K>> },
Exclude<AllKeys<T>, keyof T> | OptionalKeys<T>
> :
T;
中任何地方提到的所有属性的并集,如果它们在string
的任何元素中是可选的或缺失的,则使它们成为可选的。它可能不适用于对象和非对象类型的并集类型,但是我认为它对您的示例而言是正确的。
让我们看看:
T
看起来不错,除了T
之外,因为类型太长。让我们向上看一下以查看更多详细信息:
type WidenedScheduleUnion = Widen<Schedule_Union>
/* type WidenedScheduleUnion = {
kind: "once" | "recurring";
date?: string | undefined;
schedule?: {
kind: "weekly" | "monthly" | "dates";
weekly?: {
startDayOfWeek: string;
endDayOfWeek: string;
startDate: string;
endDate?: string | undefined;
} | undefined;
monthly?: {
...;
} | undefined;
dates?: {
...;
} | undefined;
} | undefined;
} */
这就是您想要的,对吗?好的,希望对您有所帮助。祝你好运!