Sub topic 12
Common pitfalls and how to avoid them
This chapter assumes you can already define a discriminated union and narrow it with switch, and that your tsconfig.json has strict: true. It covers the mistakes that most often make narrowing stop working, hide a missing case, or let bad data into a typed value.
All listings share one file. Later listings reuse Shape, area, and assertNever from earlier ones.
Pitfall 1: the discriminant widens to `string`
A discriminated union only narrows when the tag has a literal type such as "circle". TypeScript widens a literal to string when it infers the type of a mutable location. That includes object literal properties, let variables, and inferred function return types.
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; size: number };
function area(shape: Shape): number {
switch (shape.kind) {
case "circle":
return Math.PI * shape.radius ** 2;
case "square":
return shape.size ** 2;
}
}
function makeCircle() {
return { kind: "circle", radius: 1 };
}
// area(makeCircle()); // error: 'kind' is string, not "circle"
function makeCircleTyped(): Shape {
return { kind: "circle", radius: 1 };
}
const viaSatisfies = { kind: "circle", radius: 1 } satisfies Shape;
const viaAsConst = { kind: "circle", radius: 1 } as const;
console.log(area(makeCircleTyped()), area(viaSatisfies), area(viaAsConst));There are three fixes:
- Annotate the return type or variable with the union.
- Use
satisfies, which checks the value againstShapeand keeps the literal tag. - Use
as const, which freezes every property to its literal type and makes itreadonly.
Annotating function return types is the most reliable habit, because it also moves the error to the function that built the wrong value. Without it, the error appears at the call site.
Pitfall 2: a member with a non-literal tag
One member whose tag is string breaks narrowing for the whole union, because that member could still be "circle".
type Broken =
| { kind: "circle"; radius: number }
| { kind: string; label: string };
function radiusOf(value: Broken): number {
if (value.kind === "circle") {
// value is still Broken here: the second member may also have kind "circle".
// return value.radius; // error: 'radius' does not exist on the second member
return 0;
}
return -1;
}
console.log(radiusOf({ kind: "circle", radius: 2 }));Make every tag a literal type or a union of literals. Two related mistakes have the same effect:
- Giving two members the same tag value. The check then narrows to both members, not one.
- Making the tag optional (
kind?: "circle"). Anundefinedtag cannot identify a member.
Pitfall 3: a bag of optional properties instead of a union
A single object type with optional fields looks like a shortcut. It allows combinations that should not exist and forces a check or a non-null assertion on every read.
type LooseState = {
status: "loading" | "success" | "error";
data?: string;
error?: Error;
};
const impossible: LooseState = {
status: "loading",
data: "stale",
error: new Error("also failed"),
};
// 'impossible' compiles. A union of three members would reject it.
console.log(impossible.status);Split the type into one member per state and put each field only in the member where it exists. The earlier chapter on modeling state shows the full RequestState version.
Pitfall 4: narrowing is lost where TypeScript cannot prove it still holds
Narrowing applies to a reference at a particular point in the code. TypeScript discards it when it cannot be sure the value is unchanged. The most common case is a property path read inside a callback.
type Scene = { shape: Shape };
function totalRadius(scene: Scene, repeat: number[]): number {
if (scene.shape.kind !== "circle") return 0;
// Inside the callback, scene.shape could have been reassigned, so narrowing is reset:
// return repeat.reduce((sum) => sum + scene.shape.radius, 0); // error
const circle = scene.shape; // narrowed to the circle member
return repeat.reduce((sum) => sum + circle.radius, 0);
}
console.log(totalRadius({ shape: { kind: "circle", radius: 2 } }, [1, 2, 3]));Copy the narrowed value into a const before the callback. A const cannot be reassigned, so its narrowing carries into the closure.
Destructuring has a related limit. const { radius } = shape fails before you narrow, because radius is not on every member. Narrow the object first, then destructure inside the branch.
Pitfall 5: a missing case that nothing reports
The compiler only reports an unhandled variant if the code gives it something to check. Two patterns hide a new member.
The first is a switch without a default in a function whose return type is inferred. When you add a member, the inferred return type quietly gains undefined.
function label(shape: Shape) {
switch (shape.kind) {
case "circle":
return "round";
case "square":
return "boxy";
}
}
// Inferred return type is "round" | "boxy" today.
// Add a third member and it becomes "round" | "boxy" | undefined, with no error here.
console.log(label({ kind: "square", size: 2 }));The second is a default branch that returns a fallback. It makes every new member look handled.
function labelWithFallback(shape: Shape): string {
switch (shape.kind) {
case "circle":
return "round";
default:
return "unknown"; // a new member lands here silently
}
}
console.log(labelWithFallback({ kind: "square", size: 1 }));Use the never check from the exhaustiveness chapter and annotate the return type.
function assertNever(value: never): never {
throw new Error(`Unexpected value: ${JSON.stringify(value)}`);
}
function labelChecked(shape: Shape): string {
switch (shape.kind) {
case "circle":
return "round";
case "square":
return "boxy";
default:
return assertNever(shape);
}
}
console.log(labelChecked({ kind: "circle", radius: 1 }));Adding a member now produces a compile error at assertNever(shape). If bad data gets past the compiler at runtime, the function throws a message that names the value.
Pitfall 6: trusting data the compiler never saw
Types are erased at runtime. JSON.parse returns any, and an as Shape cast tells the compiler to stop checking.
const raw = '{"kind":"triangle","base":2}';
const unsafe = JSON.parse(raw) as Shape;
console.log(area(unsafe)); // prints undefined, although area is typed to return numberNo switch case matches "triangle", so area falls off the end. The type says number, but the value is undefined, and that value can spread through later calculations.
Validate at the boundary with a type guard. Parse into unknown, check the tag, then check the fields of that variant.
function isShape(value: unknown): value is Shape {
if (typeof value !== "object" || value === null) return false;
const v = value as Record<string, unknown>;
switch (v.kind) {
case "circle":
return typeof v.radius === "number";
case "square":
return typeof v.size === "number";
default:
return false;
}
}
const parsed: unknown = JSON.parse(raw);
if (isShape(parsed)) {
console.log(area(parsed));
} else {
console.log("Rejected: not a Shape");
}A guard is only as good as its checks. If you add a field to a member and forget to update the guard, the guard accepts bad data and the compiler cannot warn you. For large schemas, a validation library that derives the type from the schema removes that duplication.
Pitfall 7: changing the tag after construction
TypeScript lets you assign to shape.kind on a union value, because the tag's write type is the union of all tags. The assignment can leave the object with kind: "square" and a radius field. Mark the tag readonly, or the whole member.
type FrozenShape =
| { readonly kind: "circle"; readonly radius: number }
| { readonly kind: "square"; readonly size: number };
const frozen: FrozenShape = { kind: "circle", radius: 1 };
// frozen.kind = "square"; // error: cannot assign to 'kind' because it is a read-only property
console.log(frozen.kind);To change a variant, build a new object of the target variant.
Debugging checklist
When narrowing does not work, follow the questions below in order.
Summary of pitfalls
| Pitfall | Symptom | Fix |
|---|---|---|
| Widened tag | Object is not assignable to the union | Annotate, `satisfies`, or `as const` |
| `string` tag on one member | `if` check does not narrow | Use literal tags only |
| Optional-field bag | Impossible states compile | One union member per state |
| Callback closure | Narrowing resets inside the callback | Copy into a `const` |
| Silent `default` | New member goes unnoticed | `assertNever` and a return type annotation |
| `as` cast on parsed data | Wrong values at runtime | Parse as `unknown` and use a type guard |
| Mutable tag | Tag and fields disagree | `readonly` properties |
Exercise
The function below compiles, but area(makeSquare()) is rejected with an error saying kind is string. Name the cause and give two ways to fix it. function makeSquare() { return { kind: "square", size: 2 }; }
Show answer
The inferred return type widens the property kind from the literal "square" to string, so the result is not assignable to Shape. Fix it by annotating the return type (function makeSquare(): Shape) or by returning the literal with as const (return { kind: "square", size: 2 } as const;). Using satisfies Shape on the returned object also keeps the literal.
Exercise
A teammate writes const shape = JSON.parse(body) as Shape; and then calls labelChecked(shape) from the exhaustiveness section. The body is {"kind":"hexagon"}. What happens at runtime, and how should the code change?
Show answer
The compiler accepts the code because the cast hides the real type. At runtime no case matches, so the default branch calls assertNever, which throws Unexpected value: {"kind":"hexagon"}. Parse into unknown instead, check it with isShape, and handle the rejected case (for example by returning an error response) before calling labelChecked.