Command Palette

Search for a command to run...

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

The preview strips types, like Vite: a typo still runs

The second greeting has no name, so it prints Hello, !. The code runs because types are erased; only the checker (your editor or tsc) would have stopped you. // @ts-expect-error tells tsc "an error is expected on the next line", so this file still type-checks; use it only in teaching code and tests. The ! after getElementById("root") tells TypeScript the element exists (without it: Argument of type 'HTMLElement | null' is not assignable to parameter of type 'Container'.).

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'.?

The preview strips types, like Vite: a typo still runs

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

Hello, Asha! You are 9.
Hello, ! Age unknown.