Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 12.6 — TypeScript, a First Look
JavaScript · Example 3 of 3

Types are gone at run time: check outside data yourself

typeof null is "object" (an old JavaScript quirk), which is why the guard also checks value !== null. Without this guard, data.name.toUpperCase() on the third response would throw TypeError: data.name.toUpperCase is not a function, even in a fully typed TypeScript program.

TypeScript is JavaScript plus type annotations: a checker reads the types before your code runs and reports mistakes such as passing a string where a number is expected, then the types are removed and plain JavaScript runs in the browser.

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 6 hands-on exercises with automatic checks.

Practice questions

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

01

Rewrite in JavaScript (types removed): function greet(name: string, times: number = 1): string { return ("Hi " + name + "! ").repeat(times).trim(); }, then log greet("Asha", 2).

02

Write a type guard isProduct(value) that accepts objects with a string title and a positive number price. Test it on three values.

03

Add JSDoc types to function area(width, height) { return width * height; } so // @ts-check would reject area("3", 4).

Explain it without notes

01

What is TypeScript, and how does it relate to JavaScript?

02

What does it mean that TypeScript types are erased, and what are the consequences?

03

What is the difference between any and unknown?

04

In a Vite + TypeScript project, which tool checks types and which produces the JavaScript?

Types are gone at run time: check outside data yourself

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

{"name":"Asha","age":31} -> valid User, ASHA
{"name":"Ravi"} -> rejected
{"name":42,"age":"x"} -> rejected
null -> rejected