Sub topic 14
Validating Data from Outside Your Program
This chapter assumes you understand object types, union types, type narrowing, and functions. It also assumes that strict: true is enabled in your TypeScript configuration.
TypeScript checks your source code at compile time. It does not check data received at runtime. Data from JSON files, APIs, browser storage, and users can have missing fields or unexpected values. A type assertion such as value as Shape changes the compiler's view, but it does not validate the value.
Treat data from outside your program as unknown until a runtime check proves its shape.
Why a discriminated union is not runtime validation
Consider this union:
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; size: number };The compiler can use shape.kind to narrow a value that is already known to be a Shape. However, the compiler cannot guarantee that a value returned by JSON.parse matches this type.
const input: unknown = JSON.parse(
'{"kind":"circle","radius":"not a number"}',
);
// This assertion performs no runtime check.
const shape = input as Shape;
console.log(shape.radius ** 2); // Produces NaN at runtime.The assertion is unsafe because the input has a string for radius. The program must validate the discriminant and every field required by the selected variant.
Writing a custom type guard
A custom type guard is a function whose return type has the form value is SomeType. When the function returns true, TypeScript narrows the value to SomeType.
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; size: number }
| { kind: "rectangle"; width: number; height: number };
function isShape(value: unknown): value is Shape {
if (typeof value !== "object" || value === null) {
return false;
}
const object = value as Record<string, unknown>;
switch (object.kind) {
case "circle":
return typeof object.radius === "number"
&& Number.isFinite(object.radius)
&& object.radius >= 0;
case "square":
return typeof object.size === "number"
&& Number.isFinite(object.size)
&& object.size >= 0;
case "rectangle":
return typeof object.width === "number"
&& Number.isFinite(object.width)
&& object.width >= 0
&& typeof object.height === "number"
&& Number.isFinite(object.height)
&& object.height >= 0;
default:
return false;
}
}
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: unknown = JSON.parse('{"kind":"rectangle","width":4,"height":3}');
if (!isShape(parsed)) {
throw new Error("Invalid shape data");
}
console.log(area(parsed)); // 12The object assertion inside the guard is acceptable because the guard immediately checks each property before returning true. It does not claim that the original input is already a Shape.
Validation flow
A guard should check more than the tag. Validate required fields, primitive types, and important value rules such as nonnegative dimensions. If the data has nested objects or arrays, validate those recursively too.
| Input source | Safe initial type | Required next step |
|---|---|---|
| JSON API response | `unknown` | Validate before use |
| `localStorage` value | `unknown` after parsing | Validate before use |
| Internal function result | Declared union | Preserve normal narrowing |
Exercise
Why should a parsed API response be stored as unknown instead of being immediately asserted as Shape?
Show answer
JSON.parse does not verify the data. Using unknown forces a runtime guard to check the discriminant and the fields of the selected union member before the value is used.