TypeScript optional vs nullable: Why Your Generated Types Break
October 10, 2026 | 9 min read | TypeScript
By Syed · Frontend Engineer & Creator of UITweak
You paste a Supabase row into a JSON-to-TypeScript converter. It hands you bio?: string. It compiles, it ships, and two weeks later a real row comes back as "bio": null. Your Zod schema rejects it, or your strict config flags an explicit undefined somewhere in the update path, or a PATCH request clears a field you meant to leave alone. This is the typescript optional vs nullable trap: name?: string, name: string | null, and name: string | undefined look interchangeable in a generated file, but they describe three different runtime shapes, and your API can hand you all three in the same afternoon. This guide shows exactly when each one is correct, when exactOptionalPropertyTypes breaks the ? you thought was safe, and the copy-paste mapping recipes that keep generated types honest.
30-second version: Optional (?), nullable (| null), and | undefined describe key presence, not just emptiness. ? means the key may be absent. | null means the key is present with a null value. | undefined means the key is present but holds no value. JSON.parse can never produce undefined, so a converter should never emit T | undefined on its own. Check two or three real responses, map missing keys to ? and null values to | null, and turn on exactOptionalPropertyTypes only after the mapping is right.
TypeScript optional vs nullable: The Three Forms
Every "the field has no value" situation in TypeScript is one of these four declarations. Read the table first, because the rest of the guide is just this table applied to real failures:
| Declaration | Key required? | Accepts | Use when |
|---|---|---|---|
name?: string | No | string, or nothing | The field may be omitted entirely |
name: string | null | Yes | string or null | The field always arrives but can be empty (DB nullable column) |
name: string | undefined | Yes | string or undefined | JS-side "no value yet", key always present |
name?: string | undefined | No | absent, string, or undefined | Messy inputs where both absence and explicit undefined occur |
type A = { bio?: string }; // key may be absent entirely
type B = { bio: string | null }; // key always present, value may be null
type C = { bio: string | undefined }; // key always present, value may be undefined
type D = { bio?: string | undefined }; // absent, or present-with-undefined, both fine
const ok1: A = {}; // fine
const ok2: A = { bio: "hello" }; // fine
const ok3: B = { bio: null }; // fine
// const bad: B = {}; // error: bio is requiredNotice what the type checker does not tell you: whether the key exists at runtime. That is the whole trap, and it is where generated types start lying.
The Runtime Difference Your Types Hide
The classic typescript optional property undefined vs null question has a one-line runtime answer: they are different objects. undefined means "no value was ever put here"; null means "a value was deliberately cleared". The in operator sees the difference even when your types do not:
const present: { bio: string | undefined } = { bio: undefined };
const absent: { bio?: string } = {};
"bio" in present; // true: the key exists
"bio" in absent; // false: there is no key
JSON.stringify(present); // "{}" the key vanishes on the wire
JSON.stringify({ bio: null }); // '{"bio":null}' null survives as real JSONThis is why PATCH endpoints treat them differently: omitting a field means "leave it alone", sending null means "clear it". TypeScript's default mode hides the distinction because bio?: string silently accepts an explicit undefined, so {} and { bio: undefined } compile identically while behaving differently at runtime. One flag fixes the hiding.
When Generated Types Break: Two Classic Scenarios
Converters are honest only about the sample you fed them. Feed them one response and you get one of these two breaks:
Scenario 1: the key was missing in your sample
Your sample row had no nickname key, so the converter emitted nickname?: string. A later row comes back as "nickname": null (nullable column, empty for this user). The type says null is impossible, so your guard code never handles it, and a Zod schema built with .optional() rejects the row outright, because .optional() only accepts undefined, never null.
Scenario 2: the key was null in your sample
Your sample row had "bio": null, so the converter emitted bio: string | null. That is correct for the read path. Then your update form builds { bio: undefined } when the user clears the field, or you enable exactOptionalPropertyTypes and every hand written bio?: string in the codebase stops accepting explicit undefined. Both breaks come from the same root cause: the sample described one response, not the contract.
exactOptionalPropertyTypes: The Flag That Changes ?
The exactOptionalPropertyTypes compiler flag makes optional properties precise. With it on, bio?: string means the key may be omitted, period. It no longer quietly accepts an explicit undefined:
// tsconfig.json
{
"compilerOptions": {
"strict": true,
"exactOptionalPropertyTypes": true
}
}type Config = { bio?: string };
const a: Config = {}; // fine
const b: Config = { bio: "hello" }; // fine
const c: Config = { bio: undefined };
// ^ error with the flag on: undefined is not assignable to stringThe flag is not part of strict; you opt in separately. It breaks generated types in two predictable ways, both fixable:
- Break 1: callers pass explicit undefined. The fix is to say what you mean:
{ bio?: string | undefined }allows omission and explicit undefined. Use it for option bags and function parameters that receive values forwarded from other code. - Break 2: inferred types stop matching hand types. A Zod-inferred
bio?: string | undefinedis not assignable to a hand-writtenbio?: stringunder this flag. The fix is one source of truth: usez.infereverywhere instead of redeclaring the shape by hand.
When you must forward a maybe-undefined value into a strict optional property, do not assign undefined. Use the conditional spread, or give the value a default:
type Config = { bio?: string }; // flag ON
const maybeBio: string | undefined = getBio();
// recipe 1: omit the key instead of assigning undefined
const payload: Config = {
...(maybeBio === undefined ? {} : { bio: maybeBio }),
};
// recipe 2: default it
const payload2: Config = { bio: maybeBio ?? "no bio yet" };The Fix Workflow: Converter First, Mapping Rules Second
This is where the fix and our tool meet. Paste two or three real API responses into the JSON to TypeScript converter (not one): include a row with nulls, a row without the optional keys, and a row with everything filled in. Let the converter build the skeleton, then apply these mapping rules by hand:
- Key present in every response,
nullin some? The field is nullable:field: T | null. Supabase nullable columns behave exactly like this: the key is always returned, empty meansnull. - Key missing in some responses, never
null? The field is optional:field?: T. - Key missing in some responses and
nullin others? Both:field?: T | null. - Converter emitted
field?: T | undefined? It cannot know that from JSON alone, becauseJSON.parsenever producesundefined. Delete the| undefinedunless your own code assigns explicit undefined to that field.
The full walkthrough of the converter itself, including nested objects and arrays, is in our JSON to TypeScript guide. The rules above are the layer it adds on top: the converter reads samples, you read the contract.
Zod Alignment: .optional() vs .nullable() vs .nullish()
The zod optional vs nullable confusion is the same three-forms problem wearing a validation costume. .optional() accepts a missing key (value undefined) and rejects null. .nullable() requires the key to be present and accepts null. .nullish() accepts both. The rule is the same as the table above: match the schema to what the data actually does, not to what you wish it did:
import { z } from "zod";
// matches what the database and the API actually send
const ProfileSchema = z.object({
username: z.string(),
bio: z.string().nullable(), // nullable DB column: key present, may be null
nickname: z.string().optional(), // sparse PATCH body: key may be absent entirely
tagline: z.string().nullish(), // third-party feed: sometimes missing, sometimes null
});
type Profile = z.infer<typeof ProfileSchema>;
// { username: string; bio: string | null;
// nickname?: string; tagline?: string | null }The live 2026 version of this pain point: MongoDB and Supabase both store empty fields as explicit null and return the key, so a schema written with .optional() silently rejects perfectly valid rows with "expected string, received null". If a field can genuinely be either absent or null, use the single .nullish() method rather than chaining .optional().nullable(). For the full schema-writing workflow, see our JSON to Zod schema guide.
TypeScript optional vs nullable: The Decision Table
- Key may be absent entirely? Use
name?: string. In Zod, that is.optional(). - Key always present but may be empty? Use
name: string | null. In Zod, that is.nullable(). This is the Supabase nullable-column shape. - Both absence and explicit null are possible? Use
name?: string | null. In Zod,.nullish(). - Never emit
T | undefinedfrom a converter pass alone: JSON has no undefined. Add it only when your own code assigns explicit undefined. - Turning on
exactOptionalPropertyTypes? Audit every?first: callers that pass explicit undefined need?: T | undefined, and forwarded values need the conditional spread. - Keep one source of truth:
z.inferfrom the schema, or the mapped converter output, not both redeclared by hand.
Related: generate the skeleton with our JSON to TypeScript guide, then lock the contract with the JSON to Zod schema guide so runtime validation and your types can never disagree about absence again.
Frequently Asked Questions
Can a JSON API ever send undefined?
No. JSON has no undefined literal, so JSON.parse can never produce it. A key with an undefined value disappears when serialized with JSON.stringify. The only absence shapes a real API response can carry are a missing key and an explicit null, which is exactly why the converter mapping rules only need ? and | null.
Should I just use string | null | undefined everywhere?
It compiles, but it destroys the signal. When a type says bio?: string | null you know the API can omit the key or null it. When everything is | null | undefined, no one can tell whether absence means "not loaded yet", "cleared", or "the backend is inconsistent". Pick the shape from the decision table and let the type document the contract.
Does strict: true include exactOptionalPropertyTypes?
No. exactOptionalPropertyTypes is a separate opt-in flag; strict: true does not turn it on. That is why teams enable it months later and watch forty files fail at once. If you plan to adopt it, do the optional-vs-nullable mapping audit first, while the errors are still honest.
I enabled the flag and now everything fails. Fastest fix?
It is mechanical, not mysterious. For each error, decide: does the caller pass explicit undefined on purpose? Then widen the declaration to ?: T | undefined. Is the value being forwarded from another function? Use the conditional spread so the key is omitted instead of assigned undefined. Is it a default that should never have been undefined? Add ?? fallback at the boundary. Work outward from API boundaries and the list shrinks fast.