Runtime Data Validator
What you'll build
A validate function that takes a schema definition and unknown data, checks each field, and returns either a typed object or a list of errors.
Goals
- Bridge runtime validation to compile-time types
- Build a schema definition system
- Return typed success or error results
- Practice discriminated unions for results
Prerequisites
- Type guards
- Discriminated unions
- Conditional types
Steps
- 1
Define the result type
Use a discriminated union for the validation result: either success with typed data, or failure with error messages.
Codetype Result<T> = | { ok: true; value: T } | { ok: false; errors: string[] };Expected result
A Result type that represents either success or failure.
- 2
Write the schema validator
Create a simple schema validator that checks each field's type. The schema maps field names to expected type strings.
Codefunction validate<T extends Record<string, unknown>>( schema: Record<keyof T, "string" | "number" | "boolean">, data: unknown ): Result<T> { if (typeof data !== "object" || data === null) return { ok: false, errors: ["Not an object"] }; const obj = data as Record<string, unknown>; const errors: string[] = []; for (const key in schema) { if (typeof obj[key] !== schema[key]) errors.push(`${key}: expected ${schema[key]}`); } return errors.length ? { ok: false, errors } : { ok: true, value: obj as T }; }Expected result
A validator that checks data against a schema and returns a typed Result.
- 3
Use the validator
Define a schema and validate unknown data. On success, the value is typed as T, enabling safe property access.
Codeconst result = validate<{ name: string; age: number }>( { name: "string", age: "number" }, JSON.parse('{"name":"Alice","age":30}') ); if (result.ok) console.log(result.value.name); // type-safe else console.log(result.errors);Expected result
Valid data returns a typed object; invalid data returns error messages.
- 4
Add type guards & runtime checks
Write a user-defined type guard function to validate data shape at runtime, combined with the unknown type to safely handle external input. Type guards give TypeScript runtime type safety too.
Codetype User = { id: number; name: string }; function isUser(value: unknown): value is User { if (typeof value !== "object" || value === null) return false; const obj = value as Record<string, unknown>; return typeof obj.id === "number" && typeof obj.name === "string"; } // Usage with unknown input const data: unknown = JSON.parse(rawJson); if (isUser(data)) { console.log(data.name); // TS knows data is User here } else { console.error("Invalid user data"); }Expected result
When isUser returns true, TS narrows data to User type; invalid data goes to the else branch.
- 5
Add generic utility functions
Write generic utility functions (e.g., deepFreeze, groupBy) to enhance type-safe reuse. Generics let utility functions work with multiple types without losing type information.
Codefunction groupBy<T, K extends string | number>( items: T[], keyFn: (item: T) => K ): Record<K, T[]> { const result = {} as Record<K, T[]>; for (const item of items) { const key = keyFn(item); (result[key] ??= []).push(item); } return result; } // Usage const byAge = groupBy(users, u => u.age);Expected result
groupBy groups any array by key, returning a type-safe Record.
Try it yourself
What you learned
You built a runtime validator that produces compile-time typed results. This bridges the gap between untrusted runtime data (JSON, user input) and TypeScript's static type system — the core challenge of type-safe data handling.
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.