Sub topic 10
Generic Discriminated Unions
Assume you know basic TypeScript types, object types, functions, if, and switch. Also assume strict: true is enabled in tsconfig.json. This chapter builds on discriminated unions and type narrowing.
A generic discriminated union combines a type parameter with a literal-typed tag. The type parameter lets the same union describe different payload types while keeping each variant safe.
A generic state union
Consider an operation that can be idle, loading, successful, or unsuccessful. The successful state contains data, while the error state contains an error.
type RequestState<T> =
| { status: "idle" }
| { status: "loading" }
| { status: "success"; data: T }
| { status: "error"; error: Error };
function describe<T>(state: RequestState<T>): string {
switch (state.status) {
case "idle":
return "Nothing has started";
case "loading":
return "Loading";
case "success":
return `Loaded ${JSON.stringify(state.data)}`;
case "error":
return `Failed: ${state.error.message}`;
}
}
const userState: RequestState<{ id: number; name: string }> = {
status: "success",
data: { id: 7, name: "Mina" },
};
console.log(describe(userState));When T is { id: number; name: string }, the data property has that exact type in the success variant. In the error variant, error remains an Error. TypeScript does not allow code to read data before checking that status is "success".
The tag controls both narrowing and which properties are available.
flowchart TD
A[RequestState T] --> B[idle]
A --> C[loading]
A --> D[success with data T]
A --> E[error with Error]Why generics matter
Without a type parameter, you might use unknown for data. That forces every caller to check or cast the value. A generic union records the payload type at the point where the state is created.
| Type | Success payload |
|---|---|
| `RequestState<User>` | `User` |
| `RequestState<string[]>` | `string[]` |
| `RequestState<number>` | `number` |
The same function can work with every payload type because it does not need to know what T is:
function getData<T>(state: RequestState<T>): T | undefined {
if (state.status === "success") {
return state.data;
}
return undefined;
}
const names = getData<string[]>({
status: "success",
data: ["Ari", "Bo"],
});
console.log(names?.join(", "));Inside the if block, TypeScript narrows state to the success member. Therefore, state.data has type T.
The Result pattern
A common generic discriminated union represents an operation that either succeeds or fails. This is often called a Result type.
type Result<T, E> =
| { ok: true; value: T }
| { ok: false; error: E };
function parsePort(input: string): Result<number, string> {
const port = Number(input);
if (
input.trim() === "" ||
!Number.isInteger(port) ||
port < 0 ||
port > 65535
) {
return { ok: false, error: `Invalid port: ${input}` };
}
return { ok: true, value: port };
}
const result = parsePort("8080");
if (result.ok) {
console.log(`Port: ${result.value}`);
} else {
console.log(result.error);
}The boolean literal values true and false act as discriminants. A successful result cannot also contain an error, and a failed result cannot also contain a value.
Choosing type parameters
Use separate type parameters when variants carry different kinds of data. Result<T, E> uses T for the success value and E for the failure value. This lets a function return structured errors:
type Result<T, E> =
| { ok: true; value: T }
| { ok: false; error: E };
type ParseError = {
code: "empty" | "invalid";
input: string;
};
function parseCount(input: string): Result<number, ParseError> {
if (input.trim() === "") {
return { ok: false, error: { code: "empty", input } };
}
const count = Number(input);
if (!Number.isInteger(count)) {
return { ok: false, error: { code: "invalid", input } };
}
return { ok: true, value: count };
}Keep the union’s members mutually clear. If two variants have the same tag or overlapping required fields, narrowing becomes less useful.
Exercise
What type does state.data have inside if (state.status === "success") when state has type RequestState<Date>?
Show answer
It has type Date, because the generic parameter T is Date and the success member contains data: T.