TypeScript Tutorial
Add types to JavaScript — interfaces, generics, narrowing, and strict mode.
TypeScript is JavaScript with a static type system. It catches bugs before you run the code.
Basic types
let age: number = 30;
let name: string = "Ada";
let active: boolean = true;
let items: string[] = ["a", "b"];
type User = {
id: number;
email: string;
};
Interfaces and unions
interface Shape {
kind: "circle" | "square";
radius?: number;
size?: number;
}
function area(s: Shape): number {
return s.kind === "circle"
? Math.PI * (s.radius ?? 0) ** 2
: (s.size ?? 0) ** 2;
}
Generics
function first<T>(xs: T[]): T | undefined {
return xs[0];
}
const n = first([1, 2, 3]); // number | undefined
const s = first(["a", "b"]); // string | undefined
Narrowing
function format(value: string | number): string {
if (typeof value === "number") {
return value.toFixed(2); // narrowed to number
}
return value.toUpperCase(); // narrowed to string
}
Enable
"strict": trueintsconfig.json. It turns on null checks and other safety features that pay off fast.
Compiling
npx tsc # emits .js next to .ts
npx tsc --watch # recompile on change