我需要将联合对象类型(可能有嵌套联合)转换为可选值类型的深度交集。本质上,所有可能的字段都会相交,并且仅当它存在于联合的一侧时才是可选的 - 并对所有嵌套对象执行此操作。
注意:这不是简单的并集到交集
内嵌附加评论:
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;
};
Run Code Online (Sandbox Code Playgroud)
这允许使用更简单的模式来提取数据:
// 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;
Run Code Online (Sandbox Code Playgroud)
jca*_*alz 10
好吧,我要给你正在做的事情起个名字,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;
Run Code Online (Sandbox Code Playgroud)
然后我们编写一个类型,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;
Run Code Online (Sandbox Code Playgroud)
然后让我们编写一个类型Idx<T, K, D>
来查找K
type 的属性T
,不同之处在于它跨联合分布,如果没有这样的属性,则返回默认 type 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;
Run Code Online (Sandbox Code Playgroud)
一种名为PartialKeys<T, K>
which的类型与它类似Partial<T>
,只是它只作用于键K
而将其他键单独保留T
。soPartial<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;
Run Code Online (Sandbox Code Playgroud)
最后是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;
Run Code Online (Sandbox Code Playgroud)
我们对数组进行特殊处理,因为编译器会专门处理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;
} */
Run Code Online (Sandbox Code Playgroud)
这看起来是正确的,除了因为...
类型太长之外。让我们查看这些内容以了解更多详细信息:
type Monthly = NonNullable<WidenedScheduleUnion['schedule']>['monthly']
/* type Monthly = {
startDate: string;
startDayOfMonth: string;
endDayOfMonth: string;
endDate?: string | undefined;
} | undefined */
type Dates = NonNullable<WidenedScheduleUnion['schedule']>['dates']
/* type Dates = {
dateRanges: {
startDate: string;
endDate: string;
}[];
} | undefined */
Run Code Online (Sandbox Code Playgroud)
这就是你想要的,对吧?好的,希望能帮助您继续。祝你好运!
归档时间: |
|
查看次数: |
2129 次 |
最近记录: |