Handle Date Strings When Converting JSON to TypeScript
Learn how to handle ISO 8601 date strings in JSON-to-TypeScript conversion. Covers string type, Date type, branded types, and date libraries.
Detailed Explanation
Dates in JSON and TypeScript
JSON has no native date type. Dates are transmitted as strings, typically in ISO 8601 format ("2024-03-15T10:30:00Z"). This creates a gap when converting to TypeScript.
Example JSON
{
"id": 1,
"title": "Launch v2",
"createdAt": "2024-03-15T10:30:00Z",
"dueDate": "2024-04-01",
"completedAt": null
}
Option 1: Plain String (default)
interface Task {
id: number;
title: string;
createdAt: string;
dueDate: string;
completedAt: string | null;
}
This is the safest default because JSON.parse() returns strings for date values. No information is lost, but you lack type-level distinction between a date string and any other string.
Option 2: Branded Types
type ISODateString = string & { readonly __brand: "ISODateString" };
interface Task {
id: number;
title: string;
createdAt: ISODateString;
dueDate: ISODateString;
completedAt: ISODateString | null;
}
Branded types prevent accidentally assigning a regular string to a date field. You create values with a helper like const d = "2024-03-15T10:30:00Z" as ISODateString.
Option 3: Date Object Type
interface Task {
id: number;
title: string;
createdAt: Date;
dueDate: Date;
completedAt: Date | null;
}
This only works if you have a deserialization step (e.g., a Zod schema or custom reviver) that converts strings to Date objects after parsing. Raw JSON.parse() output will not match this interface.
Recommendation
Start with plain string for the generated types and add a parsing/validation layer (Zod, io-ts, or a custom transformer) that converts date strings to Date objects. This gives you both serialization safety and runtime correctness.
Use Case
You receive task data from a project management API with multiple date fields and need types that distinguish date strings from regular strings for safer date arithmetic.
Try It — JSON to TypeScript
Related Topics
Handle Optional and Nullable Fields in TypeScript from JSON
Type Refinements
Convert a Simple JSON Object to a TypeScript Interface
Basic Conversions
Type a Full API Response JSON as TypeScript
Advanced Patterns
Generate TypeScript Union Types from JSON String Values
Type Refinements
Use TypeScript Utility Types with JSON-Generated Interfaces
Complex Types