jsondecode.com logo

JSON in TypeScript — Parse, Type & Validate

TypeScript uses the same JSON.parse() and JSON.stringify() APIs as JavaScript, but adds compile-time type checking. The key challenge is typing the result of JSON.parse(), which returns any.

Parse JSON with a type assertion

Cast the result of JSON.parse() to your expected interface. This tells TypeScript what shape to expect, but does not validate at runtime.

interface User {
  id: number;
  name: string;
  email: string;
}

const jsonString = '{"id":1,"name":"Alice","email":"alice@example.com"}';
const user = JSON.parse(jsonString) as User;

console.log(user.name); // Alice

Typed JSON fetch helper

A generic helper function that fetches JSON and returns a typed result.

async function fetchJson<T>(url: string): Promise<T> {
  const res = await fetch(url);
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
  return res.json() as Promise<T>;
}

interface Post { id: number; title: string; }

const post = await fetchJson<Post>("https://api.example.com/posts/1");
console.log(post.title);

Runtime validation with Zod

Type assertions don't validate at runtime. Use Zod to parse and validate JSON against a schema.

import { z } from "zod";

const UserSchema = z.object({
  id: z.number(),
  name: z.string(),
  email: z.string().email(),
});

type User = z.infer<typeof UserSchema>;

const raw = JSON.parse(jsonString);
const user: User = UserSchema.parse(raw); // throws if invalid

Stringify with known types

JSON.stringify() works the same as in JavaScript. TypeScript will type-check the input.

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

const user: User = { id: 1, name: "Alice" };
const json = JSON.stringify(user, null, 2);
console.log(json);

Format and validate your JSON instantly

Free, no ads, no sign-up. Also converts JSON to TypeScript, YAML, CSV, and more.

Open JSON Formatter →