Zum Inhalt springen
KodeTrail

Camp 1 · Schritt 2 von 13

From JavaScript to TypeScript

Add your first type annotations — and discover how much TypeScript figures out on its own.

12 Min.+50 XPAuf Englisch angezeigt — Übersetzung ist unterwegs

Converting JavaScript to TypeScript isn't a rewrite — it's a sprinkle. Let's sprinkle.

The annotation syntax

A colon after a name declares its type:

TypeScriptCloud-Run

Three primitive types carry most programs: string, number, boolean (all lowercase). Once annotated, a variable is committed:

let km: number = 13;
km = "far";   // ❌ Type 'string' is not assignable to type 'number'

Inference: TypeScript's quiet superpower

Here's the twist — you usually don't need annotations at all:

TypeScriptCloud-Run

Initializing with a value tells TypeScript everything. let trail = "Rockies" is already typed as string — try adding trail = 99 and the compiler objects. Idiomatic TypeScript annotates function signatures and lets inference handle locals.

Typing function parameters

Parameters can't be inferred (nothing is passed yet!), so they're where annotations earn their keep:

TypeScriptCloud-Run

(km: number) types the input; : number after the parentheses types the return value.

Checkpoint

let city = 'Berlin'; — what type does TypeScript give city?

Checkpoint

Where do explicit annotations matter most?

What's next

Type errors are your new pair-programming partner — learning to read them turns red squiggles from scary to helpful.