TypeScript: Catching Bugs Before They Run Why Types, and Your First Annotations
1 / 5
Next
Why Types, and Your First Annotations ~15min

The bug types prevent

function total(price, qty) { return price * qty; }
total("450", 2);   // "450450"? No, 900. But total("450", "2") is NaN

JavaScript happily does the wrong thing. TypeScript refuses to compile it.

function total(price: number, qty: number): number {
  return price * qty;
}

It is still JavaScript

TypeScript compiles to plain JavaScript and the types vanish. They exist for the compiler and your editor. No runtime cost at all.

The basic types

let name: string = 'Amina';
let age: number = 24;
let isPro: boolean = false;
let tags: string[] = ['css', 'js'];

Let it infer

let name = 'Amina' is already known to be a string. Annotate function PARAMETERS and RETURN types, where the compiler cannot guess your intent; annotating every local variable is noise.

any defeats the purpose

any switches checking off for that value. It is occasionally a pragmatic escape hatch, but a codebase full of any is JavaScript with extra ceremony. Prefer unknown when a type is genuinely unknown. It forces you to check before using it.

Tasks
Preview