Skip to main content

TypeScript Basics

TypeScript is JavaScript with static types. Types are checked at build time and erased, so the output is plain JavaScript.

Why use it​

  • Catch typos and wrong arguments in the editor.
  • Safer refactoring and better autocomplete.
  • Self-documenting function signatures.

Basic types​

let name: string = "Asha";
let age: number = 21;
let active: boolean = true;
let scores: number[] = [90, 82];
let pair: [string, number] = ["x", 1]; // tuple

function add(a: number, b: number): number {
return a + b;
}

Objects: interface vs type​

interface User {
id: number;
name: string;
email?: string; // optional
readonly createdAt: Date; // cannot be reassigned
}

type Role = "admin" | "editor" | "viewer"; // union of literals

function canEdit(role: Role): boolean {
return role === "admin" || role === "editor";
}

Narrowing​

function format(value: string | number) {
if (typeof value === "string") {
return value.toUpperCase(); // value is string here
}
return value.toFixed(2); // value is number here
}

Generics​

function firstOr<T>(items: T[], fallback: T): T {
return items.length > 0 ? items[0] : fallback;
}

firstOr([1, 2, 3], 0); // T is number
firstOr<string>([], "none");

Useful utility types​

TypeMeaning
Partial<T>All properties optional
Required<T>All properties required
Pick<T, K>Keep only some keys
Omit<T, K>Remove some keys
Record<K, V>Object with keys K and values V

Getting started​

npm install --save-dev typescript
npx tsc --init # creates tsconfig.json
npx tsc # compile
TIP

Turn on "strict": true in tsconfig.json. It catches the most bugs, and it is much easier to start strict than to migrate later.