If you have a union type like ScheduleOrChannel
as computed here:
type AllChanges = CreateChangeLog | DeleteChangeLog
type ScheduleOrChannel = NonNullable<AllChanges["from"]>;
// type ScheduleOrChannel = Schedule | Channel
and you want to filter it to include only those union members that match a certain supertype, you can use the Extract<T, U>
utility type as shown here:
type JustSchedule = Extract<ScheduleOrChannel, { flag_active: any }>
// type JustSchedule = Schedule
type JustChannel = Extract<ScheduleOrChannel, { flag_archived: any }>
// type JustChannel = Channel
Extract<T, U>
is just a distributive conditional type which is implemented as
type Extract<T, U> = T extends U ? T : never
so you could always write your own custom union-filtering operation that uses other criteria for keeping/rejecting members, such as a HasKey
utility type:
type HasKey<T, K extends PropertyKey> =
T extends unknown ? K extends keyof T ? T : never : never;
type JustSchedule1 = HasKey<ScheduleOrChannel, "flag_active">
// type JustSchedule1 = Schedule
type JustChannel2 = HasKey<ScheduleOrChannel, "flag_archived">
// type JustChannel2 = Channel
Playground link to code