TypeScript for real code · Chapter 28 of 36
Trust nothing
By the end of this chapter you can check data that comes from outside at run time, with small schemas whose types TypeScript works out for you. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.
- Part: Real-world TypeScript
- 4 tasks
- TypeScript
- In the all labs plan
The first 2 chapters of TypeScript for real code are free. This one comes with the all labs plan.
Why you need this
An order arrives from the new Android app with the quantity as text, "2" instead of 2. Ravi saw the loyalty offer add one cup and print 21. Bunty says the types were right: his code reads JSON.parse(json) as Order.
That is the problem. Types are erased before the code runs, so they cannot check data that arrives while it runs. JSON.parse returns any, and as Order is a promise about data nobody looked at. You could write a check by hand for every shape, but then the type and the check are written twice, and one day they disagree.
What you build: 4 tasks
Each task has tests. You write the code in the lab's editor and press Check.
- Task 1
string and number: schemas that really check
string() and number() each return a schema whose parse checks an unknown value. string().parse('chai') returns 'chai', and string().parse(42) throws new Error('expected a string, got number'); string().parse(null) throws 'expected a string, got null'. number().parse(40) returns 40, number().parse('40') throws 'expected a number, got string', and number().parse(undefined) throws 'expected a number, got undefined'. Name what was received with kindOf.
Their types say what they give: string() returns a Schema<string> and number() a Schema<number>, so what parse returns is a string or a number, not any. Leave parse's parameter unknown, as Schema says, so the check is what makes the return type true.
- Task 2
Infer: the type a schema gives
Infer<S> is the type that a schema S gives when it parses, instead of any: Infer<Schema<number>> is number, Infer<Schema<string[]>> is string[], and Infer of the type of string() is string. Write it as a conditional type with infer.
- Task 3
object: check every field, and build the type from the shape
object(shape) takes an object whose values are schemas and returns a schema for objects with those fields. With s = object({ item: string(), qty: number() }): s.parse({ item: 'chai', qty: 2 }) returns { item: 'chai', qty: 2 }, and fields the shape does not name are left out, so s.parse({ item: 'chai', qty: 2, discount: 100 }) returns the same.
It throws an Error whose message starts with the field's name: s.parse({ item: 'chai' }) throws 'qty: expected a number, got undefined', and s.parse({ item: 7, qty: 2 }) throws 'item: expected a string, got number'. Inside an object inside an object the names add up: 'rider: name: expected a string, got number'. Anything that is not an object throws 'expected an object, got <what it is>', as kindOf names it: null, a string, an array.
Make it generic over the shape, <S extends Record<string, Schema<unknown>>>, so object({ item: 'masala chai' }) is a type error. Its output type is a mapped type over the shape's keys: Infer<typeof s> must be exactly { item: string; qty: number }, and an object inside an object is inferred too. One as on the finished object is allowed, inside object only.
- Task 4 · interview question
Interview: parseOrder, the schema instead of the cast
parseOrder(json) must check the JSON with orderSchema instead of trusting it with as. parseOrder('{"item":"masala chai","qty":2}') returns { item: 'masala chai', qty: 2 }, parseOrder('{"item":"masala chai","qty":"2"}') throws 'qty: expected a number, got string', and parseOrder('[]') throws 'expected an object, got array'.
Make Order the type that orderSchema gives (with Infer), so the type and the check can never drift apart: it stays exactly { item: string; qty: number }, and parseOrder returns an Order. Dev will ask what is wrong with JSON.parse(json) as Order, and why the schema fixes it.
What you will learn
- A cast is not a check: why as lets bad data through, and what a real check looks like.
- Schemas: an object whose parse checks an unknown value and returns it with a type, so the check and the type are written once.
- Types from schemas: infer reads a schema's type back out, and a mapped type builds an object's type from its fields.
More in Real-world TypeScript
Build "Trust nothing" yourself
Tapri’s codebase grows, and types keep it honest. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.
The first 2 chapters of TypeScript for real code are free. This one comes with the all labs plan.