A type is not a check
TypeScript, Flow and Elm types vanish when the program runs. If your data comes from outside, you need something that is still there at run time.
This compiles, runs, and is wrong:
interface User {
id: number
name: string
}
const user: User = await fetch('/api/me').then((r) => r.json())
console.log(user.name.toUpperCase())
r.json() returns any. The annotation : User is a promise you made to
the compiler, and the compiler believed you. If the API returns
{ "id": 1 }, the type says name is a string, and the next line throws
Cannot read properties of undefined.
The type did nothing. It was removed before the program ran.
Which types survive, and which do not
| Language | At run time |
|---|---|
| TypeScript, Flow | Gone. Erased when the program is built |
| Python type hints | Gone, unless a library reads them |
| Java, C#, Go, Rust, Swift, Kotlin | There. A cast or a decode fails loudly |
The second group is safe by accident: the decoder has to build a real object
of a real type, so it checks as it goes. Jackson throws. serde returns an
Err. JSONDecoder throws. You find out at the boundary, which is where you
want to find out.
The first group needs you to add the check.
The three ways out
1. Take the reader the generator offers
Every generator in this tool can give you more than the bare type. Turn Types only off and you get a reader that checks each field as it builds the object:
export class Convert {
public static toUser(json: string): User {
return cast(JSON.parse(json), r('User'))
}
}
That cast throws when the shape is wrong, with a message naming the field.
This is the simplest answer, it needs no package, and most people switch it
off without realising what it was for.
2. Use a schema library
Zod is the common choice, and this tool writes it:
import * as z from 'zod'
export const UserSchema = z.object({
id: z.number(),
name: z.string(),
})
export type User = z.infer<typeof UserSchema>
Two things are worth seeing here. The check and the type come from one
source, so they cannot drift apart. And UserSchema.parse(data) throws with a
path to the bad field, while safeParse gives you a result you can branch on.
Effect Schema is the same idea for a project built on Effect. Valibot is the same idea with a smaller bundle.
3. Keep a JSON Schema
If several languages read the same API, the check belongs in a JSON Schema that all of them share. Make the schema once, commit it, and generate both the types and the checking code from it in every language. The guide on sample to schema to code walks through it.
Where the check belongs
Not everywhere. A check costs time, and checking the same object five times as it moves through your program is waste.
Check at the edges, where data crosses into your program:
- an HTTP response;
- a request body you received;
- a message off a queue;
- a file you read;
- anything out of
localStorage, which the user can edit; - the result of a third-party SDK you do not trust.
Inside those edges, trust your types. That is what they are for.
What about performance?
A Zod parse of a small object is in the microseconds. For a list of a hundred thousand records it is measurable, and then you have a real choice to make: check the first record and trust the rest, check a sample, or check the shape of the list and not each item. Make that choice knowingly. Do not start by skipping the check because of a cost you never measured.
The test to run on your own code
Search your repository for as in TypeScript, or : any, or
JSON.parse(. Every result is a place where you told the compiler something
you did not verify. Most will be fine. One of them is your next incident.
Try it
Paste an API answer into the tool, pick TypeScript and read the reader it writes. Then pick Zod and compare. The second is shorter and does more, and that is why it is worth the dependency.
Try it on your own JSON. The generator runs in your browser. Nothing is uploaded, and nothing is stored on a server.
Open JSON to CodeRead next
Zod or a JSON Schema — which one should you keep?
Both check data. One lives in your TypeScript, one lives in a file every language can read. The choice depends on how many languages you have.
An enum, or a string?
A generator sees "admin" and writes string. Sometimes that is right and sometimes it throws away the most useful fact in your data.