Sub topic 14
Validating data from outside your program
This chapter assumes you have read the earlier chapters on discriminated unions, narrowing with switch, never exhaustiveness checks, and the Result type. It also assumes strict: true in your tsconfig. The goal is to connect a union type to data the compiler cannot see: JSON from a network call, a file, a message queue, or user input.
Why the compiler stops helping at the boundary
A discriminated union is a compile-time promise. The compiler checks that every piece of code handles each variant correctly. It never checks that the values at runtime match the type. TypeScript types are erased when the code is compiled to JavaScript, so nothing about Shape exists when your program runs.
Data from outside your program arrives untyped. JSON.parse returns any, which switches off checking for everything it touches. The tempting fix is a type assertion:
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; size: number }
| { kind: "rectangle"; width: number; height: number };
function area(shape: Shape): number {
switch (shape.kind) {
case "circle":
return Math.PI * shape.radius ** 2;
case "square":
return shape.size ** 2;
case "rectangle":
return shape.width * shape.height;
}
}
const parsed = JSON.parse('{"kind":"triangle","base":3}') as Shape;
console.log(area(parsed)); // prints undefined, typed as numberThis compiles without complaint. At runtime no case matches, so area falls off the end and returns undefined, even though its signature says number. The exhaustiveness check from the earlier chapter did its job, but it reasoned about a Shape that never existed.
Treat external data as unknown
The safe starting point is the type unknown. A value of type unknown can hold anything, and you cannot use it until you have narrowed it. That forces the validation step to exist in your code.
const raw: unknown = JSON.parse(text);
// raw.kind // error: 'raw' is of type 'unknown'Annotating the variable as unknown is enough. The compiler then refuses any property access until you prove something about the value. A custom type guard (a function whose return type is value is T) is how you provide that proof.
What a guard must check
A guard for a discriminated union has to verify three things, in order:
- The value is a non-null object.
typeof nullis"object", and arrays are objects too, so both need explicit handling. - The discriminant is a string that names one of the variants.
- The fields belonging to that variant have the right types.
Step 3 depends on step 2. You cannot know which fields to check until you know which variant you are dealing with. This mirrors what the compiler does when it narrows with switch (shape.kind), except that here you write the narrowing logic yourself.
Keeping the guard in sync with the type
A guard that returns value is Shape is a claim the compiler trusts without checking. If you add a variant to Shape and forget the guard, the compiler stays silent, and the guard rejects valid data forever. If you write a weaker check than the type requires, invalid data gets through.
You can make the compiler enforce completeness by keying a table of checkers on the union's tags. A mapped type over Shape["kind"] requires one entry per variant:
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; size: number }
| { kind: "rectangle"; width: number; height: number };
type Result<T, E> =
| { ok: true; value: T }
| { ok: false; error: E };
type ShapeKind = Shape["kind"];
function area(shape: Shape): number {
switch (shape.kind) {
case "circle":
return Math.PI * shape.radius ** 2;
case "square":
return shape.size ** 2;
case "rectangle":
return shape.width * shape.height;
}
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function isDimension(value: unknown): value is number {
return typeof value === "number" && Number.isFinite(value) && value >= 0;
}
const checkers: { [K in ShapeKind]: (v: Record<string, unknown>) => boolean } = {
circle: (v) => isDimension(v.radius),
square: (v) => isDimension(v.size),
rectangle: (v) => isDimension(v.width) && isDimension(v.height),
};
function isShapeKind(value: unknown): value is ShapeKind {
return (
typeof value === "string" &&
Object.prototype.hasOwnProperty.call(checkers, value)
);
}
function isShape(value: unknown): value is Shape {
if (!isRecord(value)) return false;
const kind = value.kind;
if (!isShapeKind(kind)) return false;
return checkers[kind](value);
}
function parseShape(text: string): Result<Shape, string> {
let raw: unknown;
try {
raw = JSON.parse(text);
} catch {
return { ok: false, error: "Invalid JSON" };
}
if (!isShape(raw)) {
return { ok: false, error: "Not a valid shape" };
}
return { ok: true, value: raw };
}
const inputs = [
'{"kind":"square","size":3}',
'{"kind":"triangle","base":3}',
'{"kind":"circle","radius":-1}',
"{bad",
];
for (const text of inputs) {
const result = parseShape(text);
console.log(result.ok ? area(result.value) : result.error);
}
// 9
// Not a valid shape
// Not a valid shape
// Invalid JSONThree details in this code matter.
checkersis typed with a mapped type. If you add{ kind: "triangle"; ... }toShape, the object literal is missing a property and the compiler reports an error oncheckers. The reminder you get fromassertNeverin functions now also reaches the validation code.isShapeKinduseshasOwnPropertyrather thanvalue in checkers. Theinoperator also finds inherited names, so{"kind":"toString"}would pass the check and then callObject.prototype.toStringas if it were a checker.parseShapereturns aResult. Callers cannot use the value without first testingok, so the failure path is part of the function's type instead of an exception they might forget to catch.
Edge cases the guard must handle
Each of these has bitten real code. The guard above handles them on purpose.
| Input | Naive check | What the guard does |
|---|---|---|
| `null` | `typeof null === "object"` passes | Rejected by the `!== null` test |
| `[]` | Arrays are objects | Rejected by `Array.isArray` |
| `{"size": 3}` | Missing tag reads as `undefined` | `isShapeKind(undefined)` is false |
| `{"kind":"toString"}` | `in` finds inherited keys | `hasOwnProperty` rejects it |
| `radius: NaN` | `typeof NaN === "number"` | `Number.isFinite` rejects it |
| `radius: -1` | Correct type, wrong domain | `value >= 0` rejects it |
| Extra fields | Not detected | Accepted (see below) |
JSON itself cannot encode NaN or Infinity, but data that reaches your code through other paths can. Examples are values computed in your own program, or parsers that accept extensions.
The last row is a deliberate choice. The guard accepts {"kind":"square","size":3,"color":"red"}. This matches how TypeScript treats object types, which are open: a value with extra properties is still assignable to the type. If you need a strict rejection of unknown fields, for example to catch typos in a config file, you must compare the key list yourself.
Guard bugs are invisible to the compiler
A type predicate is an unchecked claim. You could write function isShape(v: unknown): v is Shape { return true; } and the compiler would accept it. Three habits reduce this risk:
- Keep guards small and test them with both valid and invalid inputs, including the edge cases in the table.
- Write the guard next to the type, so a change to one prompts a change to the other.
- Prefer tables keyed on the union, as above, so the compiler flags missing variants.
When to use a schema library
Hand-written guards work well for a few small types. As the number of types grows, the repetition and the chance of drift grow with it. Schema libraries such as Zod and Valibot let you describe the shape once. They derive both the TypeScript type and the runtime validator from that description, so the two cannot disagree. Zod, for example, offers z.discriminatedUnion("kind", [...]) for exactly this pattern.
| Approach | Compile-time check | Runtime check | Cost |
|---|---|---|---|
| `as Shape` assertion | None | None | None, and unsafe |
| Hand-written guard | Only for the table keys | Yes | You maintain it |
| Schema library | Type derived from schema | Yes | Added dependency |
The trade-off is a dependency and a new way to describe types, in return for removing duplicated definitions. A small internal tool with two variants probably does not need one. A service that accepts many payloads from many callers probably does.
Placing the boundary
Validate once, at the edge where data enters. Everything inside the boundary then works with Shape and gets full narrowing and exhaustiveness checking, with no repeated unknown handling. Return a Result from the boundary function so that callers must deal with invalid input explicitly. Do not let any travel past that point, because it spreads through assignments without any warning.
Exercise
A colleague writes const shape = JSON.parse(body) as Shape; and says the exhaustive switch in area makes this safe. What is wrong with that reasoning, and what would you change?
Show answer
The exhaustiveness check only proves that area handles every variant of the Shape type. It cannot prove that body contains a valid Shape. The assertion hides the unchecked data from the compiler, so a payload like {"kind":"triangle"} reaches area and returns undefined. Parse into unknown, validate with a guard such as isShape, and return a Result (or throw a clear error) when validation fails.
Exercise
You add { kind: "triangle"; base: number; height: number } to Shape. Using the code in this chapter, which places produce compile errors, and what must you add to make parseShape accept triangles?
Show answer
The checkers object fails to compile because its mapped type requires a triangle entry. Any function with an exhaustive switch or an assertNever default, such as area, also fails. Add triangle: (v) => isDimension(v.base) && isDimension(v.height) to checkers and a case "triangle" to each switch. isShapeKind and isShape need no changes, because they read the keys of checkers.