Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 12.1 — Why TypeScript with React
React · Example 2 of 2

Types can't check data from outside: use unknown and a type guard

Both versions type-check with zero errors. The trusting one crashes at run time (caught here so you can read it), because the type was only a promise. The checked one gives the value the type unknown, which TypeScript won't let you use until a check proves its shape; value is User is a type guard: when isUser returns true, TypeScript treats the value as a User. Libraries such as Zod write these checks for you.

TypeScript adds types to JavaScript so a checker can catch wrong, missing and misspelled props, and values that might be null, while you type; React projects use .tsx files, the @types/react package and strict mode, and Vite strips the types without checking them.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write a typed PriceTag component with a required amount: number and an optional currency?: string that defaults to "₹". Render it twice, once without a currency.

02

Write a type guard isProduct(value: unknown): value is Product for type Product = { id: number; title: string }, use it on JSON.parse('{"id": "7", "title": "Pen"}'), and log whether the data is valid.

Explain it without notes

01

What kinds of bugs does TypeScript catch in a React app, and what kinds does it miss?

02

Vite runs your .tsx files without checking types. Where does checking happen, and why is it set up that way?

03

What does "strict": true change, and why does it matter so much for React code?

04

How do you read Type '{ nmae: string; }' is not assignable to type 'IntrinsicAttributes & GreetingProps'.?

Types can't check data from outside: use unknown and a type guard

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

trusting: TypeError: trusted.tags.map is not a function
checked: the data does not match User