Optional versus null
The difference matters when you read the value. user.email can be undefined, while user.nickname is either a string or null, so user.nickname ?? "Anonymous" handles both cases.
| In the JSON | In TypeScript | Meaning |
|---|---|---|
| Key missing from some items | email?: string | The property may not exist at all. |
Key present, sometimes null | nickname: string | null | The property always exists, but may be empty. |
| Both | nickname?: string | null | It may be missing or null. |
Give the generator enough samples
- A key that appears in every sample is marked required. If your API sometimes omits it, include an item without it.
- A key that is
nullin every sample is typed as justnull. Include one item where it has a real value, so the type becomesstring | null. - An empty array is typed
unknown[]. Put at least one item in it.
Make every field optional
For a PATCH body or a form draft where any field may be left out, keep the generated interface and wrap it with Partial, rather than adding ? by hand:
type UserPatch = Partial<UserItem>;
async function updateUser(id: number, patch: UserPatch) {
await fetch(`/api/users/${id}`, { method: "PATCH", body: JSON.stringify(patch) });
}With exactOptionalPropertyTypes
If your tsconfig.json turns on exactOptionalPropertyTypes, email?: string means the key can be left out but can't be set to undefined. If your code sets optional keys to undefined, write email?: string | undefined instead.
Frequently asked questions
Should I use interface or type for JSON data?
Either works for describing JSON. Interfaces give clearer error messages and can be extended; type aliases can also describe unions. The tool can generate both.
Do generated types check the data at runtime?
No. TypeScript types disappear when the code is compiled. To check API responses at runtime, validate them with a schema library such as Zod or with a JSON Schema validator.
Why is a nested object in an array marked optional?
It was missing from at least one item in the array. Check the samples: if it really is always there, the input JSON is incomplete.