Convert a Simple JSON Object to a TypeScript Interface
Learn how to convert a flat JSON object into a TypeScript interface with properly typed fields. Covers string, number, boolean, and null types.
Detailed Explanation
From JSON to a TypeScript Interface
The most common conversion is turning a simple, flat JSON object into a TypeScript interface. Each key in the JSON object becomes a property, and the value determines the type.
Example JSON
{
"id": 42,
"name": "Alice",
"email": "alice@example.com",
"isActive": true,
"score": 98.5
}
Generated TypeScript
interface User {
id: number;
name: string;
email: string;
isActive: boolean;
score: number;
}
How the Mapping Works
TypeScript has a direct correspondence for every JSON primitive:
| JSON type | TypeScript type |
|---|---|
| string | string |
| number | number |
| boolean | boolean |
| null | null |
Integers and floating-point numbers both map to number because JSON does not distinguish between them, and neither does TypeScript at the type level. If you need to enforce integer-only values, you can add runtime validation or use branded types.
Best Practices
- Use PascalCase for interface names (e.g.,
User,ProductDetail). - Prefer
interfaceovertypealias for object shapes when you do not need unions or intersections, since interfaces support declaration merging and can be extended. - Keep property names in camelCase to match JavaScript conventions. If your JSON uses
snake_case, the converter preserves the original keys but you may want to transform them in a mapping layer.
A simple flat object is the foundation. Once you are comfortable with this, nested objects, arrays, and optional properties are natural next steps.
Use Case
You receive a JSON payload from a REST API and want to create a type-safe interface so that your IDE provides autocompletion and catches typos at compile time.
Try It — JSON to TypeScript
Related Topics
Convert Nested JSON Objects to TypeScript Interfaces
Basic Conversions
Convert JSON Arrays of Objects to TypeScript Types
Basic Conversions
Handle Optional and Nullable Fields in TypeScript from JSON
Type Refinements
Type a Full API Response JSON as TypeScript
Advanced Patterns
Generate Readonly TypeScript Interfaces from JSON
Advanced Patterns