Sub topic 10
Generic discriminated unions
This chapter assumes you can write a basic discriminated union and narrow it with switch or if. It also assumes you know how generic functions and type aliases like Array<T> work, and that strict is on in your tsconfig.
Why make a union generic
A discriminated union fixes the shape of each variant. Some variants carry a payload whose type changes from one use to the next. A loading state might hold a User in one screen and a list of Order values in another. Copying the whole union for each payload type would repeat the same tags and the same logic.
A generic discriminated union takes the payload as a type parameter. The tags stay fixed. The payload type is supplied when you use the union.
type RequestState<T> =
| { status: "idle" }
| { status: "loading" }
| { status: "success"; data: T }
| { status: "error"; error: Error };
type User = { id: number; name: string };
type UserState = RequestState<User>;
type OrdersState = RequestState<string[]>;UserState and OrdersState share the same four tags. They differ only in the type of data inside the "success" member. Only that member mentions T. The idle, loading and error members are the same in every instantiation.
Narrowing keeps the type parameter
Narrowing works on a generic union the same way as on a concrete one. After you check the tag, TypeScript keeps only the matching member, and T stays attached to it.
type RequestState<T> =
| { status: "idle" }
| { status: "loading" }
| { status: "success"; data: T }
| { status: "error"; error: Error };
function render<T>(state: RequestState<T>, show: (data: T) => string): string {
switch (state.status) {
case "idle":
return "Waiting";
case "loading":
return "Loading...";
case "success":
return show(state.data);
case "error":
return `Failed: ${state.error.message}`;
}
}
const state: RequestState<number> = { status: "success", data: 42 };
console.log(render(state, (n) => `Answer is ${n}`));Inside case "success", state.data has type T. When you call render with a RequestState<number>, TypeScript infers T as number, so the show callback receives a number. You wrote the function once, and the compiler checks it for every payload type.
Several type parameters and defaults
A union can take more than one type parameter. Each parameter can have a constraint (extends) and a default (=). Here the error type is also configurable.
type Async<T, E extends Error = Error> =
| { status: "loading" }
| { status: "success"; data: T }
| { status: "error"; error: E };
class HttpError extends Error {
constructor(public readonly code: number, message: string) {
super(message);
}
}
const plain: Async<string> = { status: "error", error: new Error("boom") };
const http: Async<string, HttpError> = {
status: "error",
error: new HttpError(404, "Not found"),
};
if (http.status === "error") {
console.log(http.error.code);
}
if (plain.status === "error") {
console.log(plain.error.message);
}The default E = Error keeps the common case short, so Async<string> works. The constraint E extends Error rejects types such as Async<string, number>. When you pass HttpError, narrowing gives you its code property.
Writing generic helpers over the union
Generic unions become more useful when you write functions that transform them. Take a small Option type, which is either a value or nothing.
type Option<T> = { kind: "some"; value: T } | { kind: "none" };
function some<T>(value: T): Option<T> {
return { kind: "some", value };
}
const none: Option<never> = { kind: "none" };
function mapOption<T, U>(option: Option<T>, fn: (value: T) => U): Option<U> {
if (option.kind === "none") {
return option;
}
return some(fn(option.value));
}
const length = mapOption(some("hello"), (s) => s.length);
console.log(length);
console.log(mapOption(none, (n: number) => n + 1));Two details here are easy to miss.
- Returning the narrowed value as is. In the
"none"branch,optionhas type{ kind: "none" }. That member does not mentionT, so it is assignable toOption<U>unchanged. You do not need to build a new object. - Using
neverfor the empty case.Option<never>means "an option that can never hold a value". Becauseneveris assignable to every type,Option<never>is assignable toOption<number>,Option<string>, and any otherOption<T>. That is why one sharednoneconstant works everywhere.
Making the tag itself generic
Sometimes many variants share the same structure: a tag plus a payload. A helper type can build each member from a tag and a payload type.
type Tagged<K extends string, P> = { kind: K } & P;
type AppEvent =
| Tagged<"click", { x: number; y: number }>
| Tagged<"key", { key: string }>
| Tagged<"resize", { width: number; height: number }>;
function describeEvent(event: AppEvent): string {
switch (event.kind) {
case "click":
return `click at ${event.x},${event.y}`;
case "key":
return `key ${event.key}`;
case "resize":
return `resize to ${event.width}x${event.height}`;
}
}
console.log(describeEvent({ kind: "key", key: "Enter" }));The constraint K extends string makes K a literal type when you pass a string literal, so kind is "click", not string. Narrowing on event.kind works because each member of the union has a literal kind property. TypeScript sees through the intersection.
Generic helpers that select a variant
The chapter on Extract showed how to pull one member out of a union. You can wrap that idea in a generic function that works for any union with a kind tag.
type Tagged<K extends string, P> = { kind: K } & P;
type AppEvent =
| Tagged<"click", { x: number; y: number }>
| Tagged<"key", { key: string }>
| Tagged<"resize", { width: number; height: number }>;
function pick<U extends { kind: string }, K extends U["kind"]>(
items: U[],
kind: K,
): Extract<U, { kind: K }>[] {
return items.filter((item): item is Extract<U, { kind: K }> => item.kind === kind);
}
const events: AppEvent[] = [
{ kind: "click", x: 1, y: 2 },
{ kind: "key", key: "a" },
{ kind: "click", x: 5, y: 6 },
];
const clicks = pick(events, "click");
console.log(clicks.map((c) => c.x + c.y));The constraint K extends U["kind"] limits the second argument to tags that exist in the union, so pick(events, "scroll") is a compile error. The return type Extract<U, { kind: K }>[] means clicks is an array of click events, and c.x type-checks without a cast.
Pitfalls specific to generic unions
Testing the payload instead of the tag
When T can be falsy, checking the payload gives wrong answers.
type RequestState<T> =
| { status: "loading" }
| { status: "success"; data: T };
function isDone(state: RequestState<number>): boolean {
// Wrong: a successful response of 0 is treated as not done.
// return Boolean(state.status === "success" && state.data);
return state.status === "success";
}
console.log(isDone({ status: "success", data: 0 }));Always branch on the discriminant. The tag tells you which variant you have. The payload says nothing about that, especially when T is 0, "", false, or undefined.
Instantiating with a union
If you pass a union as T, the payload type is that union, and the outer union is not multiplied. RequestState<string | number> has one "success" member whose data is string | number. You still need a second narrowing step (for example typeof state.data === "string") to use the data. Do not confuse this with RequestState<string> | RequestState<number>. That type has two "success" members with the same tag. It is legal, but narrowing on status alone cannot separate them.
Forgetting that inference needs a hint
some(1) infers Option<number>. A bare none has no information, which is why it is typed as Option<never>. If you write const empty = { kind: "none" }, the tag widens to string and the object is no longer an Option at all. Annotate the constant, or use as const.
Summary of when to use which form
| Situation | Tool |
|---|---|
| Payload type varies per use | Type parameter on the union, such as `RequestState<T>` |
| Error type should be customizable | Second parameter with a constraint and a default |
| Empty variant shared across payload types | `Option<never>` constant |
| Many variants share one structure | `Tagged<K, P>` helper |
| Select a variant by tag in a helper | `Extract<U, { kind: K }>` with `K extends U["kind"]` |
Exercise
Given type Option<T> = { kind: "some"; value: T } | { kind: "none" }, write a function getOrElse<T>(option: Option<T>, fallback: T): T that returns the value when present and the fallback otherwise. Then explain why getOrElse(some(1), "x") is a compile error.
Show answer
function getOrElse<T>(option: Option<T>, fallback: T): T { return option.kind === "some" ? option.value : fallback; } In the call, T is inferred from both arguments. some(1) is an Option<number> and "x" is a string, so no single T fits both, and the compiler reports an error. Branching on option.kind narrows the union, so option.value is only read in the "some" branch.
Exercise
A RequestState<boolean> holds { status: "success", data: false }. Why is if (state.data) a poor way to detect success, and what should you check instead?
Show answer
data exists only on the success member, so the property access does not compile until you narrow, and when it does run it is false for a valid success, so the check would treat a successful response as a failure. Check the discriminant instead: if (state.status === "success"). This narrows to the success member regardless of what value T holds.