Command Palette

Search for a command to run...

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

The bug TypeScript would catch, in plain JavaScript

JavaScript ran without complaint and produced 32 items. In TypeScript, function addItems(inCart: number, extra: number) makes addItems(3, fromInput) a compile error (Argument of type 'string' is not assignable to parameter of type 'number'), because input.value is typed as string.

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?

The bug TypeScript would catch, in plain JavaScript

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

5
32
5