How to Parse JSON in TypeScript

← All guides

TypeScript uses the same JSON.parse as JavaScript, but the result is typed as any. Add an interface and, ideally, runtime validation for real type safety.

Parse with an interface

JSON.parse returns any, so assert or annotate the expected shape. Note this is a compile-time assumption, not a runtime check.

typescript
interface User {
  name: string;
  roles: string[];
}

const data = JSON.parse(text) as User;
console.log(data.name);

Validate at runtime with Zod

Because JSON.parse can't verify types, use a schema library like Zod to guarantee the data matches at runtime.

typescript
import { z } from "zod";

const User = z.object({
  name: z.string(),
  roles: z.array(z.string()),
});

const data = User.parse(JSON.parse(text)); // throws if invalid
type User = z.infer<typeof User>;

Stringify with types

JSON.stringify works the same as in JavaScript; the input type is inferred.

typescript
const json: string = JSON.stringify(data, null, 2);

Frequently Asked Questions

TypeScript can't know the runtime shape of a string, so JSON.parse returns any. Cast to an interface for compile-time help, and validate with Zod for runtime safety.

Use the JSON to TypeScript tool to produce interfaces, or JSON to Zod to get a runtime schema you can also infer types from.

No — 'as' only silences the compiler; it does not verify the data. Use a validator like Zod when the JSON comes from an untrusted source.

Related Tools