TypeScript Fundamentals
TypeScript Fundamentals
Static type checking, structural typing, generics, and discriminated unions.
The Architectural Steel Blueprint
TypeScript is a typed superset of JavaScript that compiles down to clean, plain JavaScript. It brings static verification, autocompletion, and refactoring safety to codebases.
Static Type Checking at Compile Time
TypeScript catches type errors, misspelled properties, and incorrect parameter counts during development, completely erasing all types at build time.
Structural Typing (Duck Typing)
TypeScript checks the shape of data, not nominal class names. If object A has all the required properties of type B, object A satisfies type B.
Type Aliases vs Interfaces
`interface` is ideal for open, extendable object contracts and declaration merging. `type` is required for unions, primitives, tuples, and mapped types.
Discriminated Unions
A pattern combining literal types with a shared discriminant property (e.g., `kind: "loading" | "success" | "error"`), enabling exhaustive pattern matching.
Generics ()
Enables reusable components that preserve type relationships across inputs and outputs without reverting to `any`.
Robust state modeling using Discriminated Unions and type narrowing:
// Simulating TypeScript type checking & discriminated unions
function handleApiResponse(state) {
switch (state.status) {
case "loading":
console.log("Loading spinner active...");
break;
case "success":
// In TS, state is automatically narrowed to { status: "success", data: string }
console.log("Data loaded successfully:", state.data.toUpperCase());
break;
case "error":
// Narrowed to { status: "error", error: Error }
console.error("Failed to load:", state.error.message);
break;
default: {
// Exhaustive checking: TypeScript enforces that all states are handled
const _exhaustiveCheck = state;
throw new Error("Unhandled state: " + _exhaustiveCheck);
}
}
}
handleApiResponse({ status: "success", data: "all items retrieved" });
handleApiResponse({ status: "error", error: new Error("Network timeout") });
Data loaded successfully: ALL ITEMS RETRIEVED
Failed to load: Network timeout
The "any" Contagion Trap
The Risk: Using `any` turns off type checking entirely for that variable and all downstream operations, defeating the purpose of TypeScript.
The Fix: Use `unknown` for values of uncertain type, and narrow with type guards (`typeof`, `instanceof`, or custom type predicates).
- ✓ TypeScript types exist ONLY at compile time; zero runtime performance overhead.
- ✓ Uses structural typing ("duck typing"): shapes match if required keys exist.
- ✓ Use Discriminated Unions with literal tags for bulletproof state modeling.
- ✓ Prefer `unknown` over `any` when handling untyped external inputs.
-
✓
Generics (`
`) maintain type safety across reusable functions and data structures.