The Pragmatic TypeScript Handbook
TypeScript Generics & Types: Write bulletproof code by leaning into strict mode, advanced interfaces, and mapped types.
TypeScript Generics & Types: Write bulletproof code by leaning into strict mode, advanced interfaces, and mapped types.
At its core, TypeScript is JavaScript with a safety net. Browsers have no idea what TypeScript is—they can't run it. Instead, the TypeScript compiler (tsc) checks your code for bugs while you write it, strips out every type annotation, and leaves behind clean, plain JavaScript.
If your code compiles, the types vanish. They cost zero runtime performance.
You need Node.js and a tsconfig.json to tell the compiler how strict to be and what kind of JavaScript to spit out.
# Spin up a project
npm init -y
# Install TypeScript along with tsx (a fast runner for executing TS directly in dev)
npm install -D typescript tsx
# Generate your tsconfig.json
npx tsc --init
target: "ES2022": Dictates how modern the compiled JavaScript will be.
strict: true: Turn this on immediately. It enables a suite of checks that catch the vast majority of silent JavaScript bugs.
noImplicitAny: true: Stops you from accidentally creating variables with no type checks attached.
strictNullChecks: true: Forces you to explicitly handle null and undefined instead of discovering them via production crashes.
You don't need to annotate everything. TypeScript is surprisingly smart at guessing types on its own.
// Explicit typing: use when declaring empty variables or documenting intent
let username: string = "Rahul";
let age: number = 24;
let isSubscribed: boolean = true;
// Type inference: let TypeScript do the heavy lifting
let message = "Hello";
// TypeScript already knows `message` is a string, so this errors:
// message = 42; // ❌ Type 'number' is not assignable to type 'string'
// Standard array: only holds numbers
let scores: number[] = [85, 92, 78];
// Tuple: fixed length, fixed order (great for coordinates or key-value pairs)
let httpStatus: [number, string] = [200, "OK"];
// Enum: a set of named constants
enum UserRole {
Admin = "ADMIN",
Editor = "EDITOR",
Viewer = "VIEWER"
}
let currentRole: UserRole = UserRole.Admin;
void: The function runs, does some work (like logging or writing to a DB), and returns nothing.
any: The emergency shut-off switch. It disables type-checking entirely. Avoid this—it defeats the purpose of using TypeScript.
unknown: The safe version of any. It says "I don't know what this data is yet (maybe from an API), so TypeScript won't let me touch it until I verify it."
never: Code that literally cannot finish—either an infinite loop or a function that always throws an error.
function logMessage(msg: string): void {
console.log(msg);
}
let rawPayload: unknown = '{"status": 200}';
// rawPayload.trim(); // ❌ Compiler stops you: it might not be a string!
if (typeof rawPayload === "string") {
console.log(rawPayload.trim()); // ✅ TypeScript knows it's safe now
}
function panic(errorMsg: string): never {
throw new Error(errorMsg);
}
Type your parameters and let TS infer your return types (or annotate them explicitly for public APIs).
// 'title' is optional (?); 'greeting' defaults to "Hello"
function greet(name: string, title?: string, greeting: string = "Hello"): string {
return `${greeting}, ${title ? title + " " : ""}${name}`;
}
// Defining a reusable function signature
type MathOperation = (a: number, b: number) => number;
const add: MathOperation = (x, y) => x + y;
Both define the shape of an object. In modern TypeScript, they overlap heavily, but they have distinct strengths.
Use interface when writing object-oriented code, public library APIs, or structures you might want to extend later.
Use type when you need unions, primitives, or complex type logic.
// Interface: easily extendable
interface User {
readonly id: number; // Cannot be reassigned after creation
name: string;
email?: string; // Optional field
}
// Type alias: great for unions and compound structures
type ID = string | number;
// Intersection: merging two shapes together
type Employee = User & {
salary: number;
};
Union (|): "It can be this OR that."
// Union: exact string options instead of arbitrary text
type Status = "pending" | "fulfilled" | "rejected";
interface Person { name: string; }
interface Authenticated { token: string; }
// Must satisfy both interfaces
type ActiveSession = Person & Authenticated;
const session: ActiveSession = {
name: "Aman",
token: "secret_xyz123"
};
Narrowing is how you convince TypeScript that a generic value is safe to use through standard runtime JavaScript checks (typeof, instanceof, or property checks).
The cleanest design pattern in TypeScript is the Discriminated Union—tagging related shapes with a shared literal property like kind or status:
type ApiResponse =
| { status: "success"; data: string[] }
| { status: "error"; message: string };
function handleResponse(res: ApiResponse) {
if (res.status === "success") {
// TypeScript automatically knows `data` exists here
console.log("Results:", res.data.join(", "));
} else {
// ...and here it knows only `message` exists
console.error("Failed:", res.message);
}
}
Generics are variables, but for types instead of values. They let you write flexible components without falling back to any.
// T adapts to whatever argument you pass in
function wrapInArray<T>(item: T): T[] {
return [item];
}
const numbers = wrapInArray(42); // number[]
const words = wrapInArray("hello"); // string[]
// Constraints: T must at least satisfy this shape
interface HasId { id: number; }
function logId<T extends HasId>(item: T): void {
console.log(item.id);
}
// keyof: guarantees the property exists on the object
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
const serverConfig = { port: 8080, host: "localhost" };
const port = getProperty(serverConfig, "port"); // correctly typed as number
Instead of manually rewriting types for different forms of the same model, use built-in helpers:
interface Task {
id: number;
title: string;
isDone: boolean;
}
// Makes every field optional (perfect for PATCH requests)
type TaskUpdate = Partial<Task>;
// Makes every field mandatory
type CompleteTask = Required<Task>;
// Freezes the object from mutations
type ReadonlyTask = Readonly<Task>;
// Pluck only the fields you care about
type TaskPreview = Pick<Task, "id" | "title">;
// Drop specific fields
type NewTask = Omit<Task, "id">;
// Quick dictionary/map type: keys are strings, values are Tasks
type TaskDirectory = Record<string, Task>;
Assertions are an override switch. You are telling the compiler: "Trust me, I know more about what's happening at runtime than you do."
Use them sparingly. If you're wrong, TypeScript won't save you from a runtime crash.
// 'as' casting: DOM elements default to generic types, so specify the subtype
const searchInput = document.getElementById("search-input") as HTMLInputElement;
console.log(searchInput.value);
// Non-null assertion (!): asserts that this will NOT return null
const appContainer = document.querySelector("#app")!;
| Concept | What it does | Real-world example | | --- | --- | --- | | Primitives & Inference | Basic data types; inferred automatically | let count = 0; (infers number) | | Interface / Type | Blueprint for object shapes | Domain models, API contracts | | Union (|) | Value must match one of several types | type Theme = "light" | "dark"; | | Generics (<T>) | Reusable templates preserving types | ApiResponse<T>, state stores | | Utility Types | Derives new types from existing ones | Partial<User>, Omit<Task, "id"> | | Narrowing | Shrinks broad types via runtime checks | if (typeof x === "string") |