After this lesson, you will be able to: Use TS's type system: primitives, object types, arrays, tuples, enums, literal types, unions, intersections.
Foundations. Get these right and the rest of TS makes sense.
Read each line.
// Primitiveslet n: number = 42;let s: string = "hello";let b: boolean = true;let u: undefined = undefined;let nu: null = null;let big: bigint = 100n;let sym: symbol = Symbol();// Objectstype User = { id: string; name: string; age?: number }; // age optionalconst u1: User = { id: "u1", name: "Alex" };// Arrays + tuplesconst nums: number[] = [1, 2, 3];const point: [number, number] = [1, 2]; // exactly 2 numbersconst rgb: readonly [number, number, number] = [255, 0, 0]; // immutable
The composable building blocks.
// Union, one OR the othertype Status = "loading" | "success" | "error";type Id = string | number;// Intersection, bothtype Auditable = { createdAt: Date; updatedAt: Date };type Stored<T> = T & { id: string } & Auditable;type User = Stored<{ name: string; email: string }>;// Literal typesfunction setAlign(align: "left" | "center" | "right") { /* ... */ }setAlign("center");setAlign("middle"); // Error// Discriminated union (the killer TS pattern)type Result =| { ok: true; data: User }| { ok: false; error: string };function handle(r: Result) {if (r.ok) {console.log(r.data.name); // TS knows it's the success branch} else {console.log(r.error); // TS knows it's the error branch}}
`enum Status { Pending, Active, Closed }` compiles to runtime objects. `const enum` is inlined (better perf) but breaks isolatedModules. Modern preference: literal union types (`type Status = 'pending' | 'active' | 'closed'`). Cleaner; no runtime cost. Stick to enums when you need iteration via Object.values or interop with another language.
Using `any` to silence type errors. Almost always wrong. Object type `{}` (means 'any non-null value'). Use Record<string, unknown> or unknown. `as Type` casts everywhere. Casts disable type-checking; use sparingly. Forgetting discriminated unions for state machines. They make impossible states impossible.
Pick the senior reason.
Sign in and purchase access to unlock this lesson.