Parse into unknown and check the shape before you use it: const data: unknown = JSON.parse(text); then if (isUser(data)) { … }, where isUser is a type guard returning value is User. JSON.parse(text) as User only tells the compiler what to believe: nothing is checked at runtime, and a class cast gets none of the class's methods.
JSON.parse returns any, so TypeScript lets you assign the result to any type you like and never looks at the data. That is why the popular answers (an annotation, an as cast, "casting" to a class) compile fine and then fail later with undefined fields, strings where numbers should be, or is not a function. Types disappear when the code runs, so the only way to get an object that really matches its type is to check it after parsing. The sections below show the checked approach first, then exactly what a cast does and doesn't do, how to build a real class instance, how to get Date fields back, and how to handle text that isn't JSON at all. Each example runs on this page: hit Run, then edit the input and run it again.
1Parse to unknown and check with a type guardRecommended
Store the result of JSON.parse as unknown. Unlike any, unknown lets you do nothing with the value until you have checked it. A type guard is a function whose return type is value is User: it checks each field at runtime, and wherever it returns true the compiler treats the value as a User. The value === null test is there because typeof null is "object", and JSON.parse("null") is valid. Wrap the parse and the check in one function, and the rest of your code only ever sees checked users.
interface User { id: number; name: string; active: boolean; tags: string[]; } // A type guard: true only when the value really has the shape of a User function isUser(value: unknown): value is User { if (typeof value !== "object" || value === null) return false; const v = value as Record<string, unknown>; return ( typeof v.id === "number" && typeof v.name === "string" && typeof v.active === "boolean" && Array.isArray(v.tags) && v.tags.every((tag) => typeof tag === "string") ); } function parseUser(text: string): User { const data: unknown = JSON.parse(text); if (!isUser(data)) { throw new Error(`Not a User: ${text}`); } return data; // narrowed from unknown to User } const good = '{"id": 1, "name": "Ada", "active": true, "tags": ["admin", "dev"]}'; const user = parseUser(good); console.log(user.name.toUpperCase(), user.tags.join("+")); // Valid JSON, wrong shape: id is a string and tags is missing const bad = '{"id": "2", "name": "Linus", "active": false}'; try { parseUser(bad); } catch (err) { console.log((err as Error).message); }
Output
The good input prints ADA admin+dev. The second one is valid JSON, so JSON.parse accepts it, but the guard rejects it and the function throws Not a User: {"id": "2", "name": "Linus", "active": false} before a string id can spread through the program. Skip the guard and read data.name straight from the unknown value, and this page's compiler stops with error TS2339: Property 'name' does not exist on type 'unknown'. With strict on, as in most projects, the message is error TS18046: 'data' is of type 'unknown'. Either way, the error is the point of unknown. Guards for classes, arrays and unions get their own page: check a type at runtime.
2What JSON.parse(text) as User really does
The most common answer is a one-liner: const pen: Product = JSON.parse(text) or JSON.parse(text) as Product. Both compile because any is assignable to everything, and both are fine when you control the JSON and trust it, for example a config file you wrote. But they are promises to the compiler, not checks. Here is what happens when the data doesn't keep the promise.
interface Product { name: string; price: number; } // JSON.parse returns any, so an annotation or an "as" both compile. // Neither one checks the data. const pen: Product = JSON.parse('{"name": "Pen", "price": 2.5}'); const pad = JSON.parse('{"name": "Pad", "price": "4"}') as Product; console.log(pen.price + 1); console.log(pad.price + 1); // "4" + 1 is string concatenation console.log(typeof pad.price); // A different object altogether still passes as a Product const ink = JSON.parse('{"title": "Ink"}') as Product; console.log(ink.name, ink.price); try { console.log(ink.name.toUpperCase()); } catch (err) { console.log((err as Error).message); }
Output
The matching JSON works: pen.price + 1 prints 3.5. The second object has its price as the string "4", so pad.price + 1 prints 41 and typeof pad.price prints string, while the type still says number. The third object has no name or price at all: both print undefined, and the first method call crashes with Cannot read properties of undefined (reading 'toUpperCase'), far from the line that parsed it. A double cast such as JSON.parse(text) as unknown as Product is no different: any route that ends in a cast skips the check.
3Parse JSON into a class instance
"Cast a JSON object to a class" is the most-asked version of this task, and a cast can't do it. JSON.parse always builds plain objects, so the result has the fields but not the class's prototype, which is where its methods live. To get a real instance you have to create one: copy the fields onto it with Object.assign(new Person(), data), or give the class a static fromJSON factory that checks the fields and calls the constructor.
class Person { constructor( public name = "", public born = 0, ) {} ageIn(year: number): number { return year - this.born; } // Parse, check each field, then call the real constructor static fromJSON(text: string): Person { const data: unknown = JSON.parse(text); if (typeof data !== "object" || data === null) { throw new Error("Person JSON must be an object"); } const { name, born } = data as Record<string, unknown>; if (typeof name !== "string" || typeof born !== "number") { throw new Error("Person JSON needs a string name and a number born"); } return new Person(name, born); } } const text = '{"name": "Ada", "born": 1815}'; // A cast changes the type only: the object has no prototype methods const cast = JSON.parse(text) as Person; console.log("cast:", cast instanceof Person); try { console.log(cast.ageIn(1852)); } catch (err) { console.log((err as Error).message); } // Object.assign copies the fields onto a real instance, unchecked const assigned = Object.assign(new Person(), JSON.parse(text)); console.log("assign:", assigned instanceof Person, assigned.ageIn(1852)); // A static factory checks the data and runs the constructor const ada = Person.fromJSON(text); console.log("fromJSON:", ada instanceof Person, ada.ageIn(1852)); try { Person.fromJSON('{"name": "Grace"}'); } catch (err) { console.log((err as Error).message); }
Output
The cast prints cast: false for instanceof Person, and calling the method throws cast.ageIn is not a function. Object.assign gives assign: true 37: a real instance, but the fields are copied unchecked, extra keys included, and it needs a constructor that works without arguments (the defaults name = "" and born = 0 here). The factory prints fromJSON: true 37 and rejects the incomplete object with Person JSON needs a string name and a number born. Prefer the factory when the class has invariants: the constructor stays the only way in.
4Date fields: use a reviver
JSON has no date type. JSON.stringify writes a Date as an ISO string, and JSON.parse gives that string back, so an interface field typed Date holds a string at runtime. The second argument of JSON.parse is a reviver: a function called for every key and value, whose return value replaces the parsed one. Type its value parameter as unknown and turn ISO strings into Date objects there.
interface Order { id: number; placedAt: Date; } const text = '{"id": 7, "placedAt": "2026-11-19T08:30:00.000Z"}'; // JSON has no date type: the field arrives as a string whatever the type says const raw = JSON.parse(text) as Order; console.log(typeof raw.placedAt, raw.placedAt instanceof Date); try { console.log(raw.placedAt.getUTCHours()); } catch (err) { console.log((err as Error).message); } // A reviver sees every key and value and can replace the value const ISO_DATE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z$/; function reviveDates(key: string, value: unknown): unknown { return typeof value === "string" && ISO_DATE.test(value) ? new Date(value) : value; } const order = JSON.parse(text, reviveDates) as Order; console.log(order.placedAt instanceof Date, order.placedAt.getUTCHours()); console.log(order.placedAt.toISOString()); // JSON.stringify turns the Date back into the same string console.log(JSON.stringify(order));
Output
Without the reviver the field prints string false for its typeof and instanceof Date, and calling a date method throws raw.placedAt.getUTCHours is not a function. With it, the same field prints true 8 and round-trips to 2026-11-19T08:30:00.000Z. The reviver converts values; it doesn't check the shape, so the result still needs as Order or, better, a type guard like the one in section 1 that also tests placedAt instanceof Date.
5Invalid JSON and a reusable helper
Two different things can go wrong: the text isn't JSON at all, and JSON.parse throws a SyntaxError, or it is JSON with the wrong shape. A generic helper that takes the type guard as a parameter handles both for any type and returns them as values. The result is a union with a string kind, so result.kind === "ok" narrows it to the branch that has a value.
type ParseResult<T> = | { kind: "ok"; value: T } | { kind: "error"; message: string }; // One helper for any type: JSON errors and shape errors both become values function parseJson<T>(text: string, guard: (value: unknown) => value is T): ParseResult<T> { let data: unknown; try { data = JSON.parse(text); } catch (err) { // Malformed text throws a SyntaxError const message = err instanceof SyntaxError ? err.message : String(err); return { kind: "error", message }; } return guard(data) ? { kind: "ok", value: data } : { kind: "error", message: "valid JSON, wrong shape" }; } function isNumberArray(value: unknown): value is number[] { return Array.isArray(value) && value.every((n) => typeof n === "number"); } const inputs = ["[1, 2, 3]", '[1, "2"]', "[1, 2,", "{'a': 1}", "", "null"]; for (const text of inputs) { const result = parseJson(text, isNumberArray); if (result.kind === "ok") { // result.value is number[] here console.log(`${JSON.stringify(text)} -> sum ${result.value.reduce((a, b) => a + b, 0)}`); } else { console.log(`${JSON.stringify(text)} -> ${result.message}`); } }
Output
Only [1, 2, 3] gets through, as sum 6. The mixed array and null parse but fail the guard. The truncated array and the empty string both give Unexpected end of JSON input, and single quotes are not JSON: Expected property name or '}' in JSON at position 1 (line 1 column 2). The catch block tests err instanceof SyntaxError before reading err.message. With strict on, as in most projects, a caught error has type unknown, and reading err.message directly fails with error TS18046: 'err' is of type 'unknown'. This page's compiler runs without strict, where err is any, but the instanceof check compiles in both.
6Which should you use?
| Method | Checked at runtime | Class methods | Best for |
|---|---|---|---|
| unknown + type guard | Yes | No, plain object | Data from APIs, files and users: the default |
| JSON.parse(text) as T | No | No, plain object | JSON you wrote yourself and trust |
| Object.assign(new C(), data) | No | Yes | Trusted data into a class with defaults |
| static C.fromJSON(text) | Yes | Yes | Classes with methods or invariants |
| JSON.parse(text, reviver) | Converts, does not check | Only what you build | Dates and other non-JSON types |
Frequently asked questions
Why does JSON.parse<User>(text) not compile?
JSON.parse is not generic. Its declared type is parse(text: string, reviver?: ...): any, so a type argument gives error TS2558: Expected 0 type arguments, but got 1. Write const data: unknown = JSON.parse(text) and narrow it with a type guard, or wrap the parse in your own generic helper such as parseJson<T>(text, guard) from section 5.
Does "as User" check that the JSON matches the interface?
No. as is a compile-time assertion and is erased from the output, so the object is whatever the JSON contained. A price of "4" stays a string (pad.price + 1 prints 41) and a missing field is undefined. Interfaces do not exist at runtime, so TypeScript cannot check them for you: you check the fields yourself in a type guard, or use a schema library.
How do I parse a JSON array of objects into a typed array?
Parse to unknown, then check the array and every item: Array.isArray(data) && data.every(isUser) narrows data to User[] when you put it in a type guard function isUserArray(value: unknown): value is User[]. The parseJson helper in section 5 does the same for number[], and takes any guard.
Should I use a library like zod instead of writing type guards?
For more than a few types, usually yes. Schema libraries such as zod, valibot or io-ts describe the shape once, give you the TypeScript type from it (z.infer<typeof User>), and report which field failed and why. A handwritten guard like isUser has no dependency and is fine for a handful of small types, but you have to keep it in step with the interface by hand.
How do I turn a typed object back into JSON?
Call JSON.stringify(value). It writes the own enumerable fields, so a class instance loses its methods and its class, and a Date becomes an ISO string: the order from section 4 prints {"id":7,"placedAt":"2026-11-19T08:30:00.000Z"}. Add a toJSON() method to a class to control what it writes, and use fromJSON or a reviver to read it back.
How do I read a JSON file into a typed object?
In Node, read the text with readFileSync(path, "utf8") from node:fs and pass it through the same JSON.parse plus type guard. Importing the file with import config from "./config.json" (with resolveJsonModule on) gives a type inferred from the file's contents at build time, which suits fixed config but not files that change after you compile.
Run it yourself
Open any of these in the full TypeScript editor to tweak, run and share.
TypeScript playground