Handle Optional and Nullable Fields in TypeScript from JSON

Learn how to detect optional and nullable properties when converting JSON to TypeScript. Covers the difference between undefined, null, and missing keys.

Type Refinements

Detailed Explanation

Optional vs Nullable Properties

JSON does not have the concept of "optional" — a key is either present or absent. TypeScript, however, distinguishes between optional (?), nullable (| null), and required properties.

Detecting Optionality

When converting multiple JSON samples, the converter compares keys across objects:

[
  { "id": 1, "name": "Alice", "bio": "Developer" },
  { "id": 2, "name": "Bob" }
]

Since bio is missing from the second object, it becomes optional:

interface User {
  id: number;
  name: string;
  bio?: string;
}

Handling Null Values

If a value is explicitly null, the converter adds a null union:

{ "id": 1, "name": "Alice", "deletedAt": null }
interface User {
  id: number;
  name: string;
  deletedAt: string | null;
}

Note that the converter infers string | null because deletedAt is typically a date string when present. If the only sample value is null, the type falls back to unknown | null or you can configure the tool to default to string | null.

Combined: Optional and Nullable

A field can be both optional and nullable:

interface User {
  id: number;
  name: string;
  bio?: string | null;
}

This means bio can be absent from the object, explicitly null, or a string. Use this when your API documentation states a field may be omitted entirely or set to null.

Strict Null Checks

Always enable strictNullChecks in your tsconfig.json. Without it, null and undefined are assignable to every type, and your carefully generated types lose their safety guarantees.

Use Case

Your API returns user profiles where some fields like bio, avatar, and phone number may be missing or null depending on what the user has filled in.

Try It — JSON to TypeScript

Open full tool