Optional, undefined and null
An optional field means the key may be absent, | null means the key is present but empty, and | undefined describes in-memory state, not JSON. JSON has no undefined: JSON.stringify drops such fields, so an absent key and null are different contract signals. A type should describe the contract exactly, which strict compiler options such as strictNullChecks help with, and in tests ! is better replaced by an assertion function.
TypeScript · Objects
A "clear the phone" test is green, yet an empty object went to the server. Where did the null go?
The contract says a PATCH with {"phone": null} clears the number, and an absent key leaves it unchanged. An automation engineer writes an object with phone: undefined, the test passes, yet the server never received a clear request. "The field can be empty" has three distinct forms in TypeScript, and each matches a separate situation in JSON. The lesson shows how to tell them apart so the type describes the real contract.
How it works and why. ? means the property may be absent; reading an absent property gives undefined. nick: string | undefined requires the key to exist, but its value may be undefined. closedAt: string | null means the key is always present and null is an explicit "empty" value. JavaScript itself has undefined, but JSON does not: JSON.stringify skips properties whose value is undefined and keeps null. That is why, for an API, the difference between an absent key and null matters.
interface Customer {
id: string;
phone?: string; // the key may be absent
nick: string | undefined; // the key is there, the value may be undefined
closedAt: string | null; // the key is always there, null means "not closed"
}
| Field type | Key in JSON | What it means |
|---|---|---|
phone?: string | may be absent | value not set |
nick: string | undefined | rarely makes sense in JSON | in-memory state, not on the wire |
closedAt: string | null | always present | an explicit "no value" |
The compiler helps only when the options are on. strictNullChecks (part of strict) makes null and undefined separate types; without it they can be assigned to anything. exactOptionalPropertyTypes forbids assigning an explicit undefined to a ? field unless undefined is listed in the type. noUncheckedIndexedAccess adds | undefined to index access, so rows[0].amount on an empty array no longer compiles without a check.
{
"compilerOptions": {
"strict": true,
"exactOptionalPropertyTypes": true,
"noUncheckedIndexedAccess": true
}
}
Example: "clear the phone". The type lets you write something that vanishes on the wire:
undefined or null in a PATCH
{ phone: undefined }
The key never reaches the JSON. The server sees an empty PATCH and changes nothing, while the test does not check the result.
{ phone: null }
The key goes into the JSON with null. The type string | null says plainly that this is a clear command.
interface CustomerPatch {
phone?: string;
}
// goal: clear the phone
const patch: CustomerPatch = { phone: undefined };
await request.patch('/api/customers/7', { data: patch });
// {} goes over the wire: JSON.stringify drops undefined
Without exactOptionalPropertyTypes this compiles: phone?: string allows undefined. With the option there is an error, and the author must decide what they want: drop the key or send null. The fix states the command explicitly in the type:
interface CustomerPatch {
phone?: string | null; // null = clear, absent = leave alone
}
const patch: CustomerPatch = { phone: null };
await request.patch('/api/customers/7', { data: patch });
// {"phone":null} goes over the wire
The same goes for responses: if the contract says "closedAt is always present", the test must check that rather than smooth it over with ??:
const body: unknown = await res.json();
// the only way to tell "absent" from "null"
expect(body).toHaveProperty('closedAt');
expect(body).toMatchObject({ closedAt: null });
Limits and alternatives. Types describe expectations, not reality: a server response from res.json() has to be checked at runtime. The ! operator (non-null assertion) tells the compiler "trust me" and checks nothing; in tests an assertion function is better, since it fails with a message and narrows the type:
function assertDefined<T>(v: T, msg: string): asserts v is NonNullable<T> {
if (v === undefined || v === null) throw new Error(msg);
}
const row = rows.find((r) => r.txId === id);
assertDefined(row, 'transaction ' + id + ' not found');
row.amount; // no ? and no !
expect(x).toBeDefined() gives a clear failure but does not narrow the type. The ?. and ?? operators are safe in application code, but in checks they can hide a contract regression: body.closedAt ?? null makes an absent field look like null.
Common mistakes.
- Describing a "always present, may be null" contract as
?: a regression where the backend stops sending the key goes unnoticed. - Passing
undefinedto clear a field:JSON.stringifydrops it. - Turning
strictNullChecksoff "to make it compile": half the value of types disappears. - Using
!instead of a check: the failure moves from a clear message to "Cannot read properties of undefined".
Check yourself
The API returns { "id": "1" } without closedAt, and the test has expect(body.closedAt ?? null).toBeNull(). Why is it green, and is that right if the contract requires "closedAt": null?
Answer
The ?? operator turns an absent value into null, so the check cannot tell "no key" from "key is null". For an "always present" contract, check the key (toHaveProperty) and the value separately.
What is the difference between phone?: string and phone: string | undefined, and which of them makes sense for a JSON contract?
Answer
The first allows the key to be absent, the second requires the key with a value that may be undefined. JSON has no undefined, so a meaningful contract is either an absent key (?) or an explicit null.
? means the field may be missing, while | null means the field is there but empty. Middle/Senior: For an API these are different signals, and the type must match the contract exactly. I keep strict (on by default since TypeScript 6.0), turn on exactOptionalPropertyTypes and noUncheckedIndexedAccess, remember that JSON.stringify drops undefined, and use assertion functions instead of !.