CodingNeed.

Engineering practice · 25 MIN

Validate untrusted JSON at the boundary

unknown requires evidence; a type assertion supplies none.

JSON arriving over HTTP is untrusted even when your TypeScript interface looks precise. Start with unknown, narrow object and null separately, and validate each field before constructing a trusted result. Return a discriminated union instead of mixing null, exceptions and half-valid objects. This playground transpiles types; use tsc --strict in a project to check the compile-time guarantees.

Treat the function as a small service: define a contract, maintain an invariant, and test the boundaries.

Read the example

const value: unknown = null;
console.log(typeof value);
Check the expected output
object

Your challenge

Accept unknown input. Return {ok:true,value:{name,age}} only for a non-array object whose name trims to nonempty text and age is an integer from 0 through 130. Otherwise return {ok:false,error:"Invalid learner"}. Ignore extra fields.

Solution cost: O(k) for name length k. time · O(k) for normalized output. space

Common trap

JSON.parse(text) as Learner does not validate anything at runtime.

Further reading: TypeScript: narrowing

Next lesson: Model legal state transitions