Sub topic 12
Common Pitfalls and How to Avoid Them
Assume you know basic TypeScript types, object types, functions, if, and switch. Also assume your project uses strict mode:
{
"compilerOptions": {
"strict": true
}
}Discriminated unions are reliable when every variant has a stable literal tag and the compiler can see that tag. Most problems happen when the tag is widened, made optional, changed during execution, or trusted without runtime validation.
Keep discriminants narrow
A discriminant is usually a string literal such as "circle" or "error". A string literal type accepts one exact value. The broader string type accepts any string.
Object properties can widen unexpectedly:
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; size: number };
function area(shape: Shape): number {
return shape.kind === "circle"
? Math.PI * shape.radius ** 2
: shape.size ** 2;
}
const value = { kind: "circle", radius: 2 };
// area(value); // Error: value.kind is inferred as string
const checked = { kind: "circle", radius: 2 } satisfies Shape;
console.log(area(checked));
const fixed = { kind: "circle", radius: 2 } as const;
console.log(area(fixed));Use a type annotation when you want the variable to be treated as a union member. Use satisfies when you want validation without replacing the inferred property types. Use as const when all properties should remain literal and readonly.
A type assertion such as value as Shape suppresses checking. It does not validate the object. Prefer satisfies for local values and a type guard for unknown data.
Do not make the tag optional
This design weakens narrowing:
type BadMessage =
| { kind?: "text"; text: string }
| { kind?: "image"; url: string };The compiler cannot always determine which member it has when kind is missing. Give every member a required, unique tag instead:
type Message =
| { kind: "text"; text: string }
| { kind: "image"; url: string };
function describe(message: Message): string {
if (message.kind === "text") {
return message.text;
}
return message.url;
}Do not use a truthiness check for a tag. Check the exact value:
if (message.kind === "text") {
console.log(message.text);
}A check such as if (message.kind) only proves that the value is non-empty. It does not select one union member.
Preserve the tag while changing data
A function that mutates the discriminant can make code harder to understand and can invalidate assumptions held elsewhere. Prefer returning a new value:
type Job =
| { status: "queued"; id: string }
| { status: "running"; id: string; startedAt: Date }
| { status: "done"; id: string; result: string };
function start(job: Extract<Job, { status: "queued" }>): Job {
return {
status: "running",
id: job.id,
startedAt: new Date()
};
}
console.log(start({ status: "queued", id: "job-1" }));Extract selects the union member matching a condition. It helps functions state exactly which variant they accept.
Make forgotten cases visible
A switch without an exhaustive check can silently return an incorrect default when someone adds a new variant.
function assertNever(value: never): never {
throw new Error(`Unhandled variant: ${JSON.stringify(value)}`);
}
function jobLabel(job: Job): string {
switch (job.status) {
case "queued":
return `Queued ${job.id}`;
case "running":
return `Running ${job.id}`;
case "done":
return `Done: ${job.result}`;
default:
return assertNever(job);
}
}If Job gains another status, the compiler reports an error at assertNever(job) until the new case is handled.
| Pitfall | Typical symptom | Safer approach |
|---|---|---|
| Widened tag | A valid object is rejected | Use an annotation, `satisfies`, or `as const` |
| Optional tag | Narrowing does not select a member | Make the tag required |
| Truthiness check | The wrong fields remain available | Compare the exact literal |
| Missing case | New variants reach a fallback | Call an `assertNever` helper |
Check data at runtime boundaries
TypeScript removes types when it compiles to JavaScript. It cannot inspect whether parsed JSON really matches your union. Validate the tag and the fields before using the value.
Exercise
Why can const item = { kind: "circle", radius: 1 } fail when passed to a function expecting Shape, and which two approaches preserve the literal tag?
Show answer
Its kind property may widen to string. Annotate it as Shape, or use satisfies Shape or as const.