Nullable and Unknown Data in TypeScript Interfaces
Learn to model optional and nullable fields, narrow unknown values, and safely parse API or storage data in React with strict TypeScript checks.
Optional properties may be missing, nullable fields may explicitly hold `null`, and `unknown` is useful for data that has not been checked. This guide shows React checks for each case and a type guard for settings read from storage or APIs. It also explains how to recover from malformed JSON without treating TypeScript types as runtime validation.
Nullable and Unknown Data in TypeScript Interfaces
Introduction
API and browser storage values do not arrive with TypeScript types attached. A response can omit a field, return null, or contain something unexpected. Treating every value as present can crash a React component.
Strict null checks and unknown help model that uncertainty: describe missing values, then check external input before using it.
This guide shows how to represent optional and nullable fields, then validate unknown values at API and storage boundaries.
For example, an API may omit a nickname but include an avatar field whose value is null when no image exists:
interface Profile {
nickname?: string;
avatarUrl: string | null;
}
Model optional and nullable values
Read an optional property as a value that may be undefined; a nullable property is present but may hold null. Check each case before using it in JSX:
function ProfileCard({ profile }: { profile: Profile }) {
return (
<article>
{profile.nickname !== undefined && (
<p>Also known as {profile.nickname}</p>
)}
{profile.avatarUrl === null ? (
<p>No avatar</p>
) : (
<img src={profile.avatarUrl} alt="Profile avatar" />
)}
</article>
);
}
Use unknown at data boundaries
any disables checking: you can read any property or call any method, and TypeScript will not ask whether it is valid. unknown accepts any input but requires you to narrow it first. Prefer unknown for JSON parsing, caught errors, and values read from storage.
interface Settings {
displayName: string;
compactMode: boolean;
}
function isSettings(value: unknown): value is Settings {
if (typeof value !== "object" || value === null) return false;
const candidate = value as Record<string, unknown>;
return (
typeof candidate.displayName === "string" &&
typeof candidate.compactMode === "boolean"
);
}
The assertion lets the guard inspect keys as unknown values; the checks establish the shape. This works for a small, stable format. For complex or versioned responses, a runtime schema validator can check nested fields consistently.
Parse before using API or storage data
Treat JSON.parse output as untrusted. A parser can keep invalid storage from crashing a React page:
function readSettings(raw: string | null): Settings | null {
if (raw === null) return null;
try {
const value: unknown = JSON.parse(raw);
return isSettings(value) ? value : null;
} catch {
return null;
}
}
Use the same pattern for await response.json(): treat its result as unknown, validate it, then pass typed data into UI code.
flowchart TD
A[External value] --> B{Parse succeeds?}
B -->|No| C[Use fallback or show error]
B -->|Yes| D{Shape is valid?}
D -->|No| C
D -->|Yes| E[Pass typed data to React]
Trade-Off Table
| Type choice | Use it when | Trade-off |
|---|---|---|
field?: T |
The property may be absent | Reads include undefined |
field: T | null |
The property exists but can be empty | Callers must handle null |
unknown |
Input has not been checked | Requires narrowing before use |
any |
A temporary boundary is unavoidable | Skips useful type errors throughout the code |
When to Use / When NOT to Use
Use an optional property when a field may be omitted, null when the API explicitly represents an empty value, and unknown at an unvalidated boundary. Avoid unknown after validation has produced a stable domain value; give that value a concrete type so components do not repeat the same checks.
Production Failure Scenarios
If a settings panel assumes localStorage contains valid JSON, an older saved format can make parsing throw during setup and leave the page unusable. Catch parse errors, validate required fields, then show defaults or a recovery message. Migrate known older versions explicitly.
An API may return a valid JSON object with a missing nested field, such as profile.name. Parsing succeeds, but rendering profile.name.toUpperCase() crashes. Check the shape at the boundary and show a useful error or fallback when required data is missing.
Common Pitfalls / Anti-Patterns
- Treating
value as Settingsas validation; assertions do not inspect runtime data. - Using
||when0or an empty string is valid. Use??when onlynullandundefinedshould trigger a fallback. - Disabling
strictNullChecks, which hides missing-value cases instead of handling them.
Observability Checklist
- Record the source, schema version, and parse or validation outcome.
- Track invalid record counts and request IDs.
- Alert on a rise in rejected responses without attaching raw payloads.
Security and Compliance Notes
Interfaces and type guards do not sanitize or authorize data. Validate untrusted API and storage values at runtime, and avoid logging tokens, personal data, or full payloads. Return only the fields a component needs.
Quick Recap Checklist
- Use
?for a property that may be absent and| nullfor an explicit empty value. - Keep strict null checks enabled and handle
undefinedornullbefore use. - Accept external input as
unknown; validate it at the boundary. - Give React components typed, validated data instead of raw JSON.
Interview Questions
undefined. A nullable property is present but can be null.
unknown instead of any for JSON?unknown forces code to narrow or validate the value before accessing it. any disables those checks and can hide mistakes until runtime.
null or undefined before code can use those values.
- It catches reads that assume an optional property exists.
- Keep it enabled and handle absence at the point of use.
null when the field is part of the shape but deliberately has no value.
- Use
?when the field may be omitted entirely. - Match the distinction the API or domain model actually uses.
unknown accepts input but blocks property access until the code checks it.
anyallows unchecked operations.- Narrowing creates a point where the value becomes usable.
- Stored JSON may be old, truncated, or edited by the user.
- Validate the parsed shape too, since valid JSON can still be invalid data.
- Store the result as
unknown. - Run a type guard or schema check before using it as Settings.
?? falls back only for null or undefined.
- It preserves valid values such as
0and an empty string. ||treats all falsy values as absent.
- A small stable shape can use a focused type guard.
- Both approaches must check runtime values before assigning a trusted type.
Further Reading
- For related object shape guidance, see TypeScript Objects, Arrays, and Interfaces.
- Union Types and Narrowing explains checks that make variant data safe to read.
- The post on loading and error states shows how to represent API outcomes in React.
- The TypeScript Handbook covers null and undefined.
- For parsing behavior, see MDN’s JSON.parse reference.
Conclusion
Represent absence in the type, and keep external data unknown until it passes checks. React can then handle missing fields and malformed storage without crashing.
Category
Related Posts
Objects, Arrays, and Interfaces in TypeScript
Learn how TypeScript models objects and arrays, when to use interfaces, and how to type React props while keeping untrusted runtime data safe.
Accessible React UI: Semantics, Labels, and Keyboard Use
Build React interfaces with semantic controls, connected labels, visible keyboard focus, and status announcements through practical TypeScript examples.
Advanced React State: When Local State Stops Fitting
Learn when React state needs a reducer and context, when Redux Toolkit helps, and why server data often belongs in a query cache instead.