Distributive conditional types
Relay has one RelayEvent union and many places that want a slice of it: “only the JobFailed
events”, “every event that has a jobId”. Written by hand, each slice is a copy of part of the
union. Add a new event and a copy goes stale without any error.
A conditional type can compute the slice from the union itself. That works because of one rule you must know, since it also produces some of TypeScript’s most confusing results.
The rule: conditional types distribute
Section titled “The rule: conditional types distribute”When the type being checked is a naked type parameter (just T, not T[] or [T]) and you
give it a union, TypeScript runs the condition on each member and joins the results:
type ToArray<T> = T extends unknown ? T[] : never
type A = ToArray<string | number> // string[] | number[]It is as if you wrote ToArray<string> | ToArray<number>. Without the rule you would get
(string | number)[]. The rule applies only when the parameter is checked directly and the type is
instantiated with a union.
Filtering a union
Section titled “Filtering a union”Because never vanishes from a union, returning never from a branch drops that member. That is
a filter:
type RelayEvent = | { readonly _tag: "WebhookReceived"; readonly source: string; readonly body: string } | { readonly _tag: "JobQueued"; readonly jobId: string; readonly attempt: number } | { readonly _tag: "JobFailed"; readonly jobId: string; readonly reason: string } | { readonly _tag: "JobSucceeded"; readonly jobId: string }
type PickByTag<E, Tag> = E extends { readonly _tag: Tag } ? E : nevertype EventOf<Tag extends RelayEvent["_tag"]> = PickByTag<RelayEvent, Tag>
type Failed = EventOf<"JobFailed"> // { _tag: "JobFailed"; jobId: string; reason: string }type Finished = EventOf<"JobFailed" | "JobSucceeded"> // both membersEventOf stays correct as the union grows. A new JobCancelled event is picked up by
EventOf<"JobCancelled"> the moment it is added. It also takes a union of tags, because the
member’s _tag only has to be assignable to Tag.
The helper PickByTag exists so the distribution has a naked parameter E to work on. Written
directly on RelayEvent, the condition would not distribute because RelayEvent is not a type
parameter. The built-in Extract<T, U> is this exact pattern.
You can also use the branch to compute. This one answers “which events have a jobId?” with their
tags:
type RelayEvent = | { readonly _tag: "WebhookReceived"; readonly source: string } | { readonly _tag: "JobQueued"; readonly jobId: string } | { readonly _tag: "JobFailed"; readonly jobId: string; readonly reason: string }
type TagIfHasField<E, K extends PropertyKey> = E extends { readonly _tag: infer T } ? K extends keyof E ? T : never : nevertype TagsWithField<K extends PropertyKey> = TagIfHasField<RelayEvent, K>
type WithJobId = TagsWithField<"jobId"> // "JobQueued" | "JobFailed"type WithReason = TagsWithField<"reason"> // "JobFailed"Exclude and Extract
Section titled “Exclude and Extract”Now the built-ins read as one-liners. Exclude<T, U> removes the members assignable to U;
Extract<T, U> keeps them:
type MyExclude<T, U> = T extends U ? never : Ttype MyExtract<T, U> = T extends U ? T : never
type Tag = "WebhookReceived" | "JobQueued" | "JobFailed"type JobTags = MyExtract<Tag, `Job${string}`> // "JobQueued" | "JobFailed"type NotJobs = MyExclude<Tag, `Job${string}`> // "WebhookReceived"Exclude only works on unions because it distributes. On a plain object type there is nothing to
split, and you get either the type or never.
Stopping distribution
Section titled “Stopping distribution”Sometimes you want the union as one piece. Wrap both sides of extends in a tuple. [T] is not a
naked parameter, so the check runs once:
type ToArray<T> = T extends unknown ? T[] : nevertype ToArrayAll<T> = [T] extends [unknown] ? T[] : never
type Split = ToArray<string | number> // string[] | number[]type Joined = ToArrayAll<string | number> // (string | number)[]The most common reason is never. never is an empty union, so distribution runs the condition
zero times and the whole result is never, whichever branch you hoped for:
type BadIsNever<T> = T extends never ? true : falsetype GoodIsNever<T> = [T] extends [never] ? true : false
type Bad = BadIsNever<never> // never: the condition never rantype Good = GoodIsNever<never> // truetype Other = GoodIsNever<string> // falseA real Relay case: a function that needs “no more events” as a type. A type Remaining = Exclude<Tag, Seen>
that becomes never when everything is handled is useful only if you can test for never. This
is the type-level cousin of the exhaustiveness check from M2.
Exercise
Section titled “Exercise”Write EventOf, TagsWithField, IsNever, ToArray and ToArrayAll, then use EventOf to type
select, which keeps the events of the given tags. The starter’s IsNever has the never bug
from above.
- A conditional type on a naked type parameter runs once per union member and joins the results.
- Returning
neverfrom a branch removes that member. This is howExtractandExcludework. - A helper type with a naked parameter is how you distribute over a concrete union like
RelayEvent. [T] extends [U]turns distribution off. Use it forIsNeverand when you want the union whole.- A surprising
neverresult often means distribution over an empty union.
Further reading
Section titled “Further reading”- Conditional Types:
inferand distribution.