How to Parse JSON in TypeScript
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);