For years, I had a simple, unspoken rule in TypeScript: always use undefined, never null. It worked cleanly, my types stayed simple, and I never gave it a second thought.
Then I joined my current contract.
It's a large monorepo with 50+ fullstack developers, and when it comes to empty values, it is pure chaos. Without a shared convention, everyone just guesses. Some developers reset form fields to null, others use undefined, and some use empty strings. Because data flows back and forth to a backend running Apache Avro (which explicitly turns missing values into null over the wire), null slowly bled into every corner of our React components, utility functions, and state management.
To make matters worse, strictNullChecks had been disabled from day one, eight years ago. When we finally turned it back on, TypeScript surfaced over 50,000 errors. We had to add thousands of // @ts-expect-error strict null check violation comments just to keep builds green while we chip away at the cleanup.
Staring at 50,000 nullability errors makes one thing painfully clear: "just pick whichever feels right" does not scale.
If you search Dev.to or Medium for null vs. undefined, you'll mostly find beginner definitions (typeof null === 'object') or outdated advice from the vanilla JavaScript days telling you to use null for "intentional" absence. That advice falls apart in a real-world, multi-language TypeScript architecture.
So I sat down and worked out a clear, practical standard: when null is genuinely required, when it should be strictly banned, and how to stop it from poisoning an entire codebase.
Why "Use null for Intentional Absence" Breaks Down in TypeScript
If you read older JavaScript blog posts on this topic, you'll almost always see the same advice: "Never assign undefined yourself. Leave undefined for the JavaScript engine, and always use null when you intentionally want to clear a value."
Back in the untyped ES5 days, that made sense. If you saw Cannot read properties of undefined in your browser console, you knew you had a bug: an uninitialized variable or a typo in a property name. If you saw null, you knew a developer put it there on purpose.
In modern TypeScript, that exact habit actively hurts you:
-
The compiler already catches accidental
undefined. WithstrictNullChecks(andnoUncheckedIndexedAccess), TypeScript warns you before your code ever runs if you forget to initialize a variable or access a missing key. You don't need two different runtime primitives just to debug typos. -
You can never eliminate
undefined. Optional parameters (fn(x?: string)),Array.prototype.find(), and missing object keys all evaluate toundefined. If you insist on assigningnulleverywhere, you don't replaceundefined. You end up juggling both (string | null | undefined) across your entire app.
That is why the TypeScript compiler team explicitly bans null in their own coding guidelines: "Use undefined. Do not use null."
Of course, the TypeScript compiler doesn't talk to browsers, form libraries, or Avro schemas. Web apps do. So the real question isn't "which one is better?" It's where undefined belongs, and where null is unavoidable.
Inside Your App: Keep It 100% null-Free
Inside your own TypeScript business logic, React components, and state management, undefined should be the single source of truth for "nothing here."
1. Default parameters and optional chaining just work
JavaScript's built-in ergonomics are designed around undefined, not null:
function formatDiscount(code: string | undefined = "NONE") {
return `Promo: ${code}`;
}
formatDiscount(undefined); // "Promo: NONE"
formatDiscount(null as any); // "Promo: null" -> breaks the default!
Every time null sneaks into your domain layer, default parameters silently fail, and you end up littering your components with defensive value ?? '' checks.
2. Expressing "intentional absence": name?: string vs. name: string | undefined
One valid concern from the "pro-null" camp is: "If I use undefined, how do I show that an empty value was intentional rather than forgotten?"
TypeScript gives you a much better way to express that at compile time, without touching null: separate optional properties/parameters (?) from explicitly undefinable ones (| undefined):
// ❌ Optional: easy to accidentally forget during a refactor
function updateProfile(userId: string, phoneNumber?: string) {
// ...
}
updateProfile("user-123"); // Compiles fine, even if you forgot phoneNumber!
// ✅ Required, but accepts undefined: forces an explicit decision
function updateProfileStrict(userId: string, phoneNumber: string | undefined) {
// ...
}
updateProfileStrict("user-123"); // ❌ Type error: Expected 2 arguments, but got 1.
updateProfileStrict("user-123", undefined); // ✅ Explicitly cleared/empty
When a function takes multiple parameters, param: T | undefined guarantees that every caller consciously passes a value (or explicitly passes undefined) rather than silently omitting it.
If you enable exactOptionalPropertyTypes in tsconfig.json, TypeScript enforces the same distinction on object properties too: { phoneNumber?: string } means the key can be omitted, while { phoneNumber: string | undefined } means the key must be present.
3. Forms and user input: no null in form state either
Forms are one of the biggest sources of null chaos in large teams. Developers often initialize or reset fields to null because they think "the backend expects null when this field is empty."
Keep null completely out of your form state:
-
Text inputs should use
""(empty string). React will literally warn you in the console if you passvalue={null}to a controlled<input>. -
Non-text inputs (dates, selects, custom pickers) should use
undefinedwhen uninitialized or reset.
Your UI and validation schemas (like Zod or Valibot) stay clean, predictable, and free of string | null | undefined unions. If your backend needs null when a user clears a field, that translation happens at the network boundary right before submitting, never inside your component state.
The Only Frontend Exception: Built-in Framework and DOM APIs
Frontend frameworks and browser APIs have a few unavoidable null quirks, and you'll run into them across the ecosystem:
-
React:
useRef<HTMLDivElement>(null)for DOM refs, and returningnullfrom a component to render nothing. Historically, React threw a runtime error if a component returnedundefined, which trained a generation of developers to returnnull. -
Angular:
form.reset()defaults controls tonull(unless configured withnonNullable: true), and theasyncpipe emitsnullbefore data resolves. -
Browser APIs:
document.querySelector()returnsnullwhen nothing matches, and there are similar edges elsewhere.
Treat these strictly as framework/DOM boundary quirks. Keep null contained to those touchpoints and never let it bleed into your state, props, or business logic.
The Boundaries: Where null Becomes Non-Negotiable
If undefined is so much cleaner inside TypeScript, why does null keep invading our codebases? Because your TypeScript app doesn't live in a vacuum. The moment data crosses a network boundary, a serialization layer, or a language barrier, you leave JavaScript's two-empty-values world behind.
Here are the four boundaries where null is a hard requirement, and why you must treat them differently from your internal code.
1. JSON and REST PATCH requests (omit vs. clear)
In JSON, undefined does not exist as a data type. When you call JSON.stringify(), properties with undefined values are silently stripped out:
JSON.stringify({ name: "Vlad", phone: undefined }); // '{"name":"Vlad"}'
JSON.stringify({ name: "Vlad", phone: null }); // '{"name":"Vlad","phone":null}'
In a REST PATCH endpoint, that distinction is critical:
-
undefined(omitted key): "Leavephoneuntouched in the database." -
null(explicit key): "Clearphonein the database."
This is why your form state should stay "" or undefined while the user edits. If your API uses these omit/clear semantics, your submit mapper converts cleared fields to null right before calling fetch or axios.
2. Multi-language backends (Java, Python, Rust)
Most backend languages only have one concept of "nothing," and when serialized to JSON, it becomes null:
-
Java / Kotlin:
nullserializes to JSONnull. -
Python:
Noneserializes to JSONnull. -
Rust:
Option::None(viaserde_json) serializes to JSONnullby default.
Your backend engineers aren't trying to ruin your TypeScript types. Their runtime literally has no undefined primitive to send you.
3. GraphQL
GraphQL schemas are built around null. Any nullable field in a GraphQL query returns null when absent, never an omitted key or undefined. If you run GraphQL Code Generator straight into your UI components without transforming the output, T | null will immediately infect every prop and hook in your frontend.
4. Binary and schema formats: Apache Avro vs. Protobuf
If you work with event-driven architectures or strict RPC contracts (like the monorepo I mentioned at the start), serialization formats dictate how absence is represented on the wire:
-
Apache Avro: Avro has no concept of
undefinedor implicit optionality. Nullable fields are modeled explicitly as union types in the schema, like["null", "string"], so missing values are serialized directly asnull. If you consume generated Avro TypeScript types directly in your React state,nullis baked into every single field. -
Protobuf (proto3): Protobuf takes a different approach. Historically, proto3 used zero-value defaults (
"",0,false) for missing fields. With modern optional field presence and TypeScript generators like@bufbuild/protobuf, unset optional fields map much more naturally toundefined, which avoids thenullflood you get with Avro or GraphQL.
The Fix: Push the null Boundary to the Backend Serialization Layer
You cannot stop Apache Avro, Protobuf, or a relational database from speaking null. What you can do is keep that translation strictly in the backend serialization layer, allowing your entire frontend to stay 100% null-free, even at its network boundary.
Instead of forcing every frontend developer to remember when to convert undefined or "" into null, the backend (or BFF) owns the contract.
1. Frontend: 100% null-free, even over the wire
When your API contract uses undefined (omitted keys) or empty strings for missing values, the frontend never touches null: not in form state, not in React components, and not in outgoing fetch payloads:
// Frontend form & API payload: zero nulls anywhere
interface UpdateUserRequest {
nickname?: string; // omitted if untouched
bio: string; // "" if cleared
}
await api.patch("/users/123", {
nickname: form.nickname ?? undefined,
bio: form.bio.trim(),
});
2. Backend: translate undefined ↔ null at the Avro / Protobuf edge
Your backend domain logic also stays null-free (undefined only). Only the thin serializer/deserializer layer converts missing values into null right before encoding for Avro union schemas (["null", "string"]) or Protobuf wire contracts:
// Internal backend domain model (100% null-free)
interface UserDomainEvent {
userId: string;
referralCode: string | undefined;
}
// Generated Avro / Protobuf wire type
interface UserWireRecord {
userId: string;
referralCode: string | null;
}
// Outgoing serializer: explicitly convert missing values -> null for Avro/Protobuf
export function toWireRecord(event: UserDomainEvent): UserWireRecord {
return {
userId: event.userId,
referralCode: event.referralCode ?? null,
};
}
// Incoming deserializer: strip wire nulls -> undefined immediately on arrival
export function fromWireRecord(record: UserWireRecord): UserDomainEvent {
return {
userId: record.userId,
referralCode: record.referralCode ?? undefined,
};
}
What About Translating at the UI Boundary Instead?
You can put a null ↔ undefined mapper (using Zod .nullable().transform() or API adapters) at your frontend's network layer. If you consume a third-party GraphQL or external REST API that you don't control, you have to.
However, in a fullstack monorepo where you own the backend, doing it in the UI is less ideal:
-
It blurs the rule for frontend developers. Instead of a blanket "zero nulls in frontend code" rule, developers have to remember which folders allow
nulland which don't. -
It duplicates translation work. Multiple frontend views or clients end up mapping the same
nullpayloads that a single backend serializer could have normalized once at the source.
Enforce It with a Lint Rule So Nobody Has to Argue in PRs
In a 50+ developer monorepo, style guides in Notion get ignored. Automate the rule instead:
- Enable
strictNullChecks: true(and ideallyexactOptionalPropertyTypes: true) intsconfig.json. - Turn on
unicorn/no-nullacross your frontendsrc/folders, and only disable it inside yourapi/,serializers/, ormappers/directories.
Final Thought
We are still right in the middle of untangling those 50,000+ @ts-expect-error suppressions. Honestly, the biggest win so far hasn't been burning down the old backlog. It has been stopping the bleeding in new code.
When 50+ developers share a monorepo, "just be careful with null" is not a strategy. Establishing a hard architectural border changed the conversation overnight:
-
Inside TypeScript:
undefinedis our single source of truth (usingprop: T | undefinedwhen we want explicit intent, and""orundefinedin form state). -
At the edges:
nullis strictly a wire-format concern, translated immediately at our Avro, GraphQL, and REST boundaries before it ever touches a component. - In CI: ESLint enforces the rule automatically, so nobody has to argue about it in PR reviews.
If your codebase feels like a minefield of T | null | undefined, stop treating null vs. undefined as a stylistic preference. Treat it as an architectural boundary problem: ban null inside your app, normalize it at the edges, and let the compiler do its job.
Top comments (0)