Course contentsShow
← TypeScript
Lesson 987 of 1,79623. Type AssertionsFree lesson

Assertions with JSON.parse

Since `JSON.parse` returns `any`, assert the expected shape: `const data = JSON.parse(str) as MyType`.

Assertions with JSON.parse

What you'll learn: How to safely type data from JSON.parse() using type assertions, since it returns the unsafe any type by default.


The Problem: JSON.parse Returns any

When you call JSON.parse(), TypeScript assigns it the any type because there's no way to know at compile time what shape the JSON string contains:

const jsonString = '{"name": "Alice", "age": 30}';
const data = JSON.parse(jsonString); // type: any

This any completely bypasses type safety. You can access any property without errors, even ones that don't exist:

console.log(data.nonExistent.property); // No compile error, runtime crash!

The Solution: Assert the Expected Shape

Since you typically know what structure you expect from your JSON, use a type assertion to tell TypeScript what shape to expect:

type User = {
  name: string;
  age: number;
};

const jsonString = '{"name": "Alice", "age": 30}';
const data = JSON.parse(jsonString) as User;

console.log(data.name); // TypeScript knows this exists
console.log(data.age);  // And this too

Now TypeScript treats data as a User object, giving you autocomplete and type checking.


The Reality Check

Remember: assertions don't validate at runtime. If the JSON actually contains different data, TypeScript won't catch it:

const badJson = '{"title": "Book"}'; // Wrong shape!
const data = JSON.parse(badJson) as User;
console.log(data.name); // undefined at runtime, no compile error

Think of assertions with JSON.parse as a promise to TypeScript about what the string contains. You're responsible for ensuring that promise is true—TypeScript won't verify it for you.


Key Takeaway: Since JSON.parse returns any, use as YourType to restore type safety based on the shape you expect, but remember this is purely a compile-time hint with no runtime validation.