FE·16
TypeScript
A structural type system layered on JavaScript: primitives, interfaces, unions, narrowing, generics, and type-level programming (keyof, mapped, conditional and template literal types, infer), compared with Java, Rust and Go generics. Plus the rule that types vanish at run time, so you validate with schemas.
Start here: why add types to JavaScript
Three bugs JavaScript lets through
Here's a small cart in plain JavaScript, with three mistakes a tired programmer could make:
const cart = [{ name: "Masala dosa", price: 90, qty: 2 }, { name: "Filter coffee", price: 30, qty: 1 }];
function total(items) { return items.reduce((sum, item) => sum + item.price * item.qty, 0); }
const extra = inputValue(); // a delivery charge typed into a form: "40"
console.log("total:", total(cart) + extra);
console.log("first item:", cart[0].nmae); // typo
console.log("rounded:", total(cart).toFixd(2)); // typo
total: 21040
first item: undefined
TypeError: total(...).toFixd is not a function
JavaScript ran all of it. The first bug silently produced ₹21,040 (210 joined to the string "40"); the second silently printed undefined; only the third crashed, and only when that line actually ran. In a real app, these surface as customer complaints days later.
TypeScript: JavaScript plus a checker
TypeScript is JavaScript with type annotations, plus a compiler (tsc) that checks them before the code runs. The same cart:
type CartItem = { name: string; price: number; qty: number };
const cart: CartItem[] = [
{ name: "Masala dosa", price: 90, qty: 2 },
{ name: "Filter coffee", price: 30, qty: 1 },
];
function total(items: CartItem[]): number {
return items.reduce((sum, item) => sum + item.price * item.qty, 0);
}
function inputValue(): string { return "40"; }
const extra = inputValue();
const grand: number = total(cart) + extra;
console.log("first item:", cart[0].nmae);
console.log("rounded:", total(cart).toFixd(2));
$ npx tsc
cart.ts(15,7): error TS2322: Type 'string' is not assignable to type 'number'.
cart.ts(16,36): error TS2339: Property 'nmae' does not exist on type 'CartItem'.
cart.ts(17,37): error TS2551: Property 'toFixd' does not exist on type 'number'. Did you mean 'toFixed'?
All three found, with line and column, without running anything. Your editor shows the same errors as red underlines while you type, and autocompletes cart[0]. with name, price and qty. That's most of TypeScript's value: mistakes caught at your desk instead of in production, and an editor that knows your data.
Two things TypeScript is not: it's not a different language (every JavaScript program is already valid TypeScript, and the output is plain JavaScript); and it doesn't check anything at run time. The types are erased when compiled, which matters a great deal later in this section.
Annotations and inference
You annotate with : type after a name:
let cups: number = 0;
const dish: string = "Idli";
const open: boolean = true;
const prices: number[] = [90, 50, 30];
function addTax(amount: number, rate: number = 0.05): number { return amount * (1 + rate); }
But you rarely need to write that much. TypeScript infers types from values: let cups = 0 is already a number, and addTax's return type is inferred from its body. The usual style is: annotate function parameters and data shapes, and let inference do the rest.
Describing objects: type and interface
Name the shapes of your data once, then use the name everywhere:
type Dish = {
name: string;
price: number;
veg: boolean;
spiceLevel?: number; // ? = optional: may be missing (its type is number | undefined)
readonly id: string; // can't be changed after creation
};
interface Customer { // interface: another way to name an object shape
name: string;
phone: string;
}
type and interface overlap almost entirely for object shapes; teams usually pick one style. type can also name unions and other types (next), which is why many codebases default to it.
Union types: one of several
A union (A | B) says "a value of one of these types". Combined with literal types (specific values as types), unions model real states precisely:
type OrderStatus = "placed" | "cooking" | "ready" | "delivered";
let s: OrderStatus = "redy";
error TS2820: Type '"redy"' is not assignable to type 'OrderStatus'. Did you mean '"ready"'?
When a value could be one of several types, TypeScript makes you check which before using type-specific features. This is narrowing: an if, switch, typeof or === check tells the compiler more about the value inside that branch:
type Order = { id: string; status: OrderStatus; table?: number; items: string[] };
function label(o: Order): string {
switch (o.status) {
case "placed": return "We've got your order";
case "cooking": return "In the kitchen";
case "ready": return o.table !== undefined ? `Ready for table ${o.table}` : "Ready for pickup";
case "delivered": return "Enjoy!";
}
}
The most useful pattern in TypeScript is the discriminated union: several object shapes that share a "kind" field, so checking that field tells the compiler which shape you have:
type Payment =
| { kind: "upi"; vpa: string }
| { kind: "card"; last4: string; network: "visa" | "rupay" | "mastercard" }
| { kind: "cash" };
function describe(p: Payment): string {
if (p.kind === "upi") return `UPI ${p.vpa}`; // here p is the upi shape
if (p.kind === "card") return `${p.network} card ending ${p.last4}`; // here p is the card shape
return "Cash at counter";
}
rupay card ending 4242 | UPI asha@okbank
Try to read p.vpa without checking kind first, and the compiler stops you, because a cash payment has no VPA:
error TS2339: Property 'vpa' does not exist on type 'Payment'.
Property 'vpa' does not exist on type '{ kind: "cash"; }'.
null and undefined: the billion-dollar mistake, handled
With the strict option on (the default since TypeScript 6.0; never turn it off), null and undefined are separate types that must be handled before use:
function greet(name: string | undefined) { return name.toUpperCase(); }
error TS18048: 'name' is possibly 'undefined'.
That one check eliminates the "Cannot read properties of undefined" errors that dominate JavaScript bug reports. Fix it by narrowing (if (name) …), a default (name ?? "guest"), or optional chaining (name?.toUpperCase()).
Generics: functions that work for any type, safely
A generic function takes a type parameter, written in angle brackets, so it can work with any type while keeping the connection between its input and output types:
function firstOr<T>(items: T[], fallback: T): T {
return items.length > 0 ? items[0] : fallback;
}
firstOr([3, 5], 0); // T is number → 3
firstOr<string>([], "none"); // T is string → "none"
firstOr([1, 2], "none");
error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.
You've already used generics: CartItem[] is shorthand for Array<CartItem>, and Promise<User> is a promise that will produce a User.
Types disappear at run time
The compiler deletes every type when it produces JavaScript. So a type is a claim, checked only against your own code. When data comes from outside (an API, a form, localStorage), nothing checks that it matches:
type User = { id: number; name: string; email: string };
const user = (await (await fetch("/me")).json()) as User; // "as" tells the compiler: trust me
console.log(user.name.toUpperCase());
Against a server that actually returned {"id": "17", "full_name": "Asha K"}:
as User → crashed: Cannot read properties of undefined (reading 'toUpperCase')
id + 1 → 171
It compiled without complaint and failed at run time, the same way plain JavaScript does. The rule: at the boundaries of your program, check data at run time (with a validation function or a schema library such as Zod, covered in the full-depth section), and only then give it a type. Inside your program, trust the types.
How deep to go in TypeScript
Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.
| Level | What you can do |
|---|---|
| L1 | Read annotations, object types, unions and generics |
| L2 | Type an app's data, functions and components in strict mode; narrow unions; use utility types |
| L3 | Explain structural typing, assignability and variance, inference, conditional and mapped types, declaration files and module resolution |
| L4 | Diagnose confusing errors, unsound escapes (any, as, !), slow type-checking and boundary data that doesn't match its type |
| L5 | Design type-safe APIs and domain models (discriminated unions, branded types, schemas shared with the backend) |
| L6 | Run TypeScript across a monorepo: project references, build speed, upgrade strategy, the native compiler |
What TypeScript is
A type checker that erases itself
TypeScript is JavaScript plus a static type system. The compiler (tsc, or a faster transpiler such as esbuild, SWC or Babel that only strips types) checks your code and then erases the types, producing plain JavaScript. Nothing about TypeScript's types exists at run time. That one fact explains most of its design:
- It must describe existing JavaScript patterns (dynamic objects, overloads by convention,
undefinedeverywhere) rather than impose a new model. - It's gradual:
anyopts out, and you can type a codebase incrementally. - It's intentionally unsound in a few places (covered under soundness below), trading proof for practicality.
- Runtime validation is a separate job (covered at the end of this chapter).
function total(items: { price: number; qty: number }[]): number {
return items.reduce((sum, i) => sum + i.price * i.qty, 0);
}
total([{ price: 10, qty: "2" }]); // compile error: Type 'string' is not assignable to type 'number'
Run tsc --noEmit in CI to type-check, and let the bundler strip types. Node 22.6+ and 23 can run .ts files directly by stripping types (--experimental-strip-types, enabled by default in recent Node versions), and Deno and Bun run TypeScript natively. Microsoft rewrote the compiler in Go (project Corsa): TypeScript 7.0, released in 2026, is the native compiler, with multi-threaded checking that Microsoft reports at around 10× faster on large codebases. TypeScript 6.0 (March 2026) was the last JavaScript-based release and the bridge to it: it made strict the default, defaulted module to esnext and target to the latest ECMAScript, set types to an empty list, and deprecated old options (target: es5, moduleResolution: node10, AMD/UMD/SystemJS output, baseUrl, outFile) that 7.0 removes. With TypeScript 7, passing files on the command line while a tsconfig.json is present is an error unless you add --ignoreConfig.
The essential compiler options
// tsconfig.json — a strict modern baseline
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "Bundler", // or "NodeNext" for Node libraries
"strict": true, // turns on the strict family below; always on
"noUncheckedIndexedAccess": true, // arr[i] is T | undefined: catches out-of-range reads
"exactOptionalPropertyTypes": true, // `x?: string` doesn't accept an explicit undefined
"noImplicitOverride": true,
"verbatimModuleSyntax": true, // explicit `import type`; plays well with transpilers
"isolatedModules": true, // each file transpilable alone (esbuild/SWC requirement)
"skipLibCheck": true,
"jsx": "react-jsx"
}
}
strict enables strictNullChecks (the most valuable flag: null and undefined are separate types, the cure for Hoare's billion-dollar mistake from Vol. 1 ch. 2), noImplicitAny, strictFunctionTypes, strictPropertyInitialization, useUnknownInCatchVariables, and more.
Basic types
Primitive and special types
| Type | Values | Notes |
|---|---|---|
string, number, boolean, bigint, symbol |
The JS primitives | Lowercase. String (capitalised) is the wrapper object type: don't use it |
null, undefined |
Themselves | Distinct under strictNullChecks |
T[] / Array<T>, readonly T[] |
Arrays | |
[string, number] |
Tuples: fixed length and positions | [x: number, y: number] with labels; optional [a: string, b?: number]; rest [string, ...number[]] |
object |
Any non-primitive | |
unknown |
Anything, but you must narrow before use | The safe top type. Use it for untrusted input and catch (e) |
any |
Anything, and type checking is switched off | Contagious: avoid it. ESLint no-explicit-any |
never |
No values | Bottom type: functions that throw, exhaustive checks (below) |
void |
"Return value ignored" | Function returns |
Type inference (Vol. 1 ch. 10) means you annotate less than in Java. Annotate function parameters and exported function return types (they're contracts), and let locals be inferred:
let n = 5; // number
const c = 5; // 5: a *literal* type, since const can't change
const xs = [1, "a"]; // (string | number)[]
const point = { x: 1, y: 2 } as const; // { readonly x: 1; readonly y: 2 }: deeply readonly literals
const config = { mode: "dark" } satisfies Config; // check against Config but keep the narrow inferred type
satisfies (TS 4.9) validates that a value matches a type without widening it to that type. You get both the error checking and the precise inferred type, so config.mode stays "dark".
Interfaces and type aliases
Both name an object shape:
interface User {
readonly id: string; // can't be reassigned through this type
name: string;
email?: string; // optional: string | undefined (strictly: may be absent)
roles: Role[];
greet(): string; // method
[key: `data-${string}`]: string; // index signature with a template literal key pattern
}
type Point = { x: number; y: number };
type Id = string | number; // aliases can name ANY type: unions, tuples, functions, primitives
type Handler = (event: Event) => void;
interface |
type alias |
|
|---|---|---|
| Object shapes | ✓ | ✓ |
| Unions, tuples, primitives, mapped/conditional types | ✗ | ✓ |
extends |
interface B extends A |
Intersection A & {…} |
| Declaration merging (reopen and add members) | ✓ | ✗ |
| Error messages and performance | Named in errors; cached | Expanded in some errors |
A common convention: use interface for public object contracts that consumers may extend, and type for everything else. Many teams simply use type everywhere. Both are fine; consistency matters more.
Structural typing
TypeScript's type system is structural (Vol. 1 ch. 2): a value is assignable to a type if it has the required shape, whatever it's called or where it came from. This is like Go interfaces, but applied to every type, and unlike Java, C# or Rust, which are nominal.
interface Named { name: string }
class Dog { constructor(public name: string, public breed: string) {} }
const n: Named = new Dog("Rex", "lab"); // OK: Dog has `name`, so it's a Named. No `implements` needed
function area(p: { w: number; h: number }) { return p.w * p.h; }
const box = { w: 2, h: 3, colour: "red" };
area(box); // OK: extra properties are fine for variables…
area({ w: 2, h: 3, colour: "red" }); // …but an error for fresh object LITERALS ("excess property check")
The excess property check on fresh object literals catches typos like { colr: "red" } that structural typing would otherwise allow.
Branded types: nominal typing on purpose
Structural typing means UserId and OrderId are interchangeable if both are string. That's the units-mixing bug from Vol. 1 ch. 2's newtype discussion. Branded (or opaque) types add a phantom property so they become incompatible, at zero run-time cost:
type Brand<T, B extends string> = T & { readonly __brand: B };
type UserId = Brand<string, "UserId">;
type OrderId = Brand<string, "OrderId">;
type Cents = Brand<number, "Cents">;
const asUserId = (s: string): UserId => s as UserId; // the ONLY place casting happens (after validation)
function getOrder(id: OrderId) { /* … */ }
const uid = asUserId("u_42");
getOrder(uid); // error: Type 'UserId' is not assignable to type 'OrderId'
getOrder("o_1"); // error: plain string isn't an OrderId either
This is the equivalent of Rust's struct UserId(String) newtype, Java's records or value classes, and Go's type UserId string (which is nominal in Go). Schema libraries can produce branded types after validating (Zod's .brand()). Brand IDs, money amounts, sanitised HTML (SafeHtml), and validated emails.
Unions, intersections and narrowing
Union types
A union A | B is a value that is one of several types. It's TypeScript's sum type (Vol. 1 ch. 2):
type Status = "idle" | "loading" | "success" | "error"; // union of string literal types: a lightweight enum
function setStatus(s: Status) {}
setStatus("loading"); // ✓
setStatus("done"); // ✗ compile error: typo caught
type Id = string | number;
function format(id: Id) {
return id.toUpperCase(); // ✗ error: toUpperCase doesn't exist on number. You must narrow first
}
On a union you can only use members common to every member, until you narrow.
Literal types
Literal types are types whose only value is one specific string, number or boolean: "GET", 404, true. Combined with unions, they replace most uses of enums:
type Method = "GET" | "POST" | "PUT" | "DELETE";
const METHODS = ["GET", "POST", "PUT", "DELETE"] as const;
type Method2 = (typeof METHODS)[number]; // derive the union from a runtime array: one source of truth
Avoid TypeScript enum in new code. Numeric enums are unsound (any number is assignable), enums emit runtime code (which conflicts with "types are erased" and with Node's type stripping, which rejects them), and const enum breaks under isolated transpilation. Use literal unions plus as const objects:
const Role = { Admin: "admin", Editor: "editor", Viewer: "viewer" } as const;
type Role = (typeof Role)[keyof typeof Role]; // "admin" | "editor" | "viewer"
Narrowing
Narrowing is how the checker refines a union to a specific member inside a branch, by understanding JavaScript's own runtime checks. It's control-flow analysis:
function describe(x: string | number | Date | null | undefined) {
if (x == null) return "nothing"; // equality: removes null and undefined
if (typeof x === "string") return x.toUpperCase(); // typeof guard
if (x instanceof Date) return x.toISOString(); // instanceof guard
return x.toFixed(2); // only number remains
}
function area(s: Circle | Square) {
if ("radius" in s) return Math.PI * s.radius ** 2; // `in` guard
return s.side ** 2;
}
Discriminated unions are the most important TypeScript pattern. Each member has a common literal property (the discriminant, or tag), and switching on it narrows precisely, just like Rust's match on enum variants or Java 21's sealed interfaces with pattern-matching switch:
type RequestState<T> =
| { status: "idle" }
| { status: "loading" }
| { status: "success"; data: T }
| { status: "error"; error: Error };
function render(s: RequestState<User[]>) {
switch (s.status) {
case "idle": return "Start searching";
case "loading": return "Loading…";
case "success": return `${s.data.length} users`; // s.data available only here
case "error": return `Failed: ${s.error.message}`;
default: return assertNever(s); // exhaustiveness check
}
}
function assertNever(x: never): never {
throw new Error(`Unhandled case: ${JSON.stringify(x)}`);
}
Add a fifth status and assertNever(s) stops compiling, because s is no longer never. That gives you Rust- and Zig-style exhaustiveness. The design also makes illegal states unrepresentable: you can't have data and error at the same time, unlike the common { loading: boolean; data?: T; error?: Error } shape, which allows four contradictory combinations.
User-defined type guards and assertion functions extend narrowing to your own checks:
function isUser(x: unknown): x is User { // type predicate
return typeof x === "object" && x !== null && "id" in x && typeof (x as any).id === "string";
}
function assertDefined<T>(v: T, msg?: string): asserts v is NonNullable<T> {
if (v == null) throw new Error(msg ?? "value is null or undefined");
}
const raw: unknown = JSON.parse(body);
if (isUser(raw)) raw.id; // raw is User in this branch
assertDefined(config.apiUrl); config.apiUrl.length; // narrowed after the call
Since TS 5.5, simple predicate-like functions (such as x => x !== null in .filter) are inferred as type guards automatically.
Intersections
An intersection A & B is a value that has all members of both:
type Timestamped = { createdAt: Date; updatedAt: Date };
type Entity<T> = T & Timestamped & { id: string };
type UserEntity = Entity<{ name: string }>; // { name; createdAt; updatedAt; id }
Intersecting incompatible types produces never (string & number). Branded types are intersections. Interfaces' extends is usually clearer and faster to check than large intersections.
Generics
Generic functions, types and classes
Generics parameterise code over types (Vol. 1 ch. 2's parametric polymorphism):
function first<T>(xs: readonly T[]): T | undefined { return xs[0]; }
first([1, 2, 3]); // T inferred as number
interface ApiResponse<T> { data: T; meta: { page: number; total: number } }
type UsersResponse = ApiResponse<User[]>;
class Cache<K, V> {
#map = new Map<K, V>();
get(key: K): V | undefined { return this.#map.get(key); }
set(key: K, value: V): this { this.#map.set(key, value); return this; }
}
async function fetchJson<T>(url: string): Promise<T> {
const res = await fetch(url);
return res.json() as Promise<T>; // ⚠ an unchecked assertion: see runtime validation below
}
How TypeScript generics compare with the strategies from Vol. 1 ch. 2:
| Implementation | At run time | Variance | |
|---|---|---|---|
| TypeScript | Full erasure: generics disappear completely; one JS function serves all T | No trace of T: no new T(), no T.name, no reflection |
Structural, mostly inferred; in/out annotations available |
| Java | Erasure to the bound | Class<T> tokens needed for reflection |
Invariant; use-site wildcards (? extends) |
| Rust | Monomorphisation | Each T compiled separately | Inferred (mainly for lifetimes) |
| Go | GC-shape stenciling + dictionaries | Partially reified | Invariant |
| C++ | Template instantiation | Each T compiled separately | N/A |
Constraints
extends in a type-parameter list constrains what T may be, like Java's <T extends Comparable<T>>, Rust's trait bounds and Go's constraints:
function longest<T extends { length: number }>(a: T, b: T): T {
return a.length >= b.length ? a : b;
}
longest("hello", "hi"); // ✓ strings have length
longest([1, 2], [1, 2, 3]); // ✓ arrays too
longest(10, 20); // ✗ number has no length
function getProp<T, K extends keyof T>(obj: T, key: K): T[K] { // K must be a key of T
return obj[key];
}
getProp(user, "email"); // type: string | undefined
getProp(user, "emial"); // ✗ caught
function merge<A extends object, B extends object>(a: A, b: B): A & B { return { ...a, ...b }; }
function withDefault<T = string>() {} // default type parameter
const type parameters (TS 5.0) infer literal types as if the caller wrote as const: function tuple<const T extends readonly unknown[]>(...xs: T): T.
Variance
Variance (Vol. 1 ch. 2) says how subtyping of T relates to subtyping of Box<T>. TypeScript measures it structurally from how T is used:
- Covariant (output positions: return types, readonly properties):
Catis a subtype ofAnimal, so() => Catis a subtype of() => Animal. ✓ - Contravariant (input positions: parameters):
(a: Animal) => voidis a subtype of(c: Cat) => void. A handler for any animal can handle cats. - Invariant: both reading and writing.
- Bivariant: TypeScript checks method parameters bivariantly, and also function-typed properties when
strictFunctionTypesis off. That's one of its deliberate unsound spots.
const cats: Cat[] = [];
const animals: Animal[] = cats; // allowed: arrays are treated covariantly…
animals.push(new Dog()); // …so this compiles, and now cats contains a Dog. Java arrays have the
// same hole (ArrayStoreException); TS doesn't even throw. Use readonly arrays.
Explicit variance annotations (interface Producer<out T>, Consumer<in T>, <in out T>) document and enforce the intent, and speed up checking in large type graphs.
Type-level programming
TypeScript's type system is a small functional language of its own, Turing-complete in fact, that runs at compile time: compare C++ templates and Zig comptime (Vol. 1 ch. 2). Its building blocks follow.
keyof and indexed access types
interface User { id: string; name: string; age: number }
type UserKey = keyof User; // "id" | "name" | "age"
type NameType = User["name"]; // string: indexed access
type Values = User[keyof User]; // string | number
type Item = Order["items"][number]; // element type of an array property
type FirstArg = Parameters<typeof fn>[0];
typeof in a type position gets the type of a value. That's how you derive types from runtime constants instead of duplicating them (as const objects, config, routes).
Mapped types
A mapped type builds a new object type by iterating over keys, a for…in loop over types:
type Optional<T> = { [K in keyof T]?: T[K] }; // = Partial<T>
type ReadonlyDeep<T> = { readonly [K in keyof T]: T[K] extends object ? ReadonlyDeep<T[K]> : T[K] };
type Mutable<T> = { -readonly [K in keyof T]: T[K] }; // -readonly / -? remove modifiers
type Getters<T> = { [K in keyof T as `get${Capitalize<string & K>}`]: () => T[K] }; // key remapping
type G = Getters<{ name: string; age: number }>; // { getName: () => string; getAge: () => number }
type OnlyStrings<T> = { [K in keyof T as T[K] extends string ? K : never]: T[K] }; // filter keys
Utility types
The built-in utility types are all defined with mapped and conditional types:
| Utility | Result | Typical use |
|---|---|---|
Partial<T> / Required<T> |
All properties optional / required | PATCH bodies, defaults |
Readonly<T> |
All properties readonly (shallow) |
Props and state |
Pick<T, K> / Omit<T, K> |
Keep or drop keys | Omit<User, "password"> for public DTOs |
Record<K, V> |
An object with keys K and values V | Record<Status, string> labels; exhaustive maps |
Exclude<U, X> / Extract<U, X> |
Remove or keep union members | Exclude<Status, "idle"> |
NonNullable<T> |
Remove null and undefined |
|
ReturnType<F> / Parameters<F> / ConstructorParameters<C> / InstanceType<C> |
Function and class introspection | Typing wrappers and mocks |
Awaited<T> |
Unwrap promises (recursively) | Awaited<ReturnType<typeof load>> |
NoInfer<T> (5.4) |
Block inference from this position | Make one parameter decide T |
Uppercase, Lowercase, Capitalize, Uncapitalize |
String literal transforms | Template literal types |
Record<Status, string> is a cheap exhaustiveness check for lookup tables: adding a status makes every table that's missing it fail to compile.
Conditional types
Conditional types choose a type based on a test, T extends U ? X : Y, which is the type-level if:
type IsString<T> = T extends string ? true : false;
type A = IsString<"hi">; // true
// DISTRIBUTIVE over unions when T is a naked type parameter:
type ToArray<T> = T extends unknown ? T[] : never;
type B = ToArray<string | number>; // string[] | number[] (applied to each member)
type C = [string | number] extends [unknown] ? 1 : 0; // wrap in [] to stop distribution
type NonNull<T> = T extends null | undefined ? never : T; // how NonNullable/Exclude work: `never` drops a member
Template literal types
Template literal types manipulate string literal types with the same syntax as JavaScript template strings:
type Side = "top" | "right" | "bottom" | "left";
type Margin = `margin-${Side}`; // "margin-top" | "margin-right" | …
type EventName<T extends string> = `on${Capitalize<T>}`;
type Handlers = { [E in "click" | "focus" as EventName<E>]: (e: Event) => void }; // { onClick; onFocus }
type Route = "/users/:id/posts/:postId";
type Params<R extends string> =
R extends `${string}:${infer P}/${infer Rest}` ? P | Params<`/${Rest}`> :
R extends `${string}:${infer P}` ? P : never;
type P = Params<Route>; // "id" | "postId": typed route params
Type-safe routers (TanStack Router, React Router's typegen), CSS-in-TS libraries, and event emitters use these techniques.
infer
infer declares a type variable inside a conditional type's test, capturing part of a matched type. It's type-level pattern matching with bindings:
type ElementOf<T> = T extends readonly (infer E)[] ? E : never;
type U = ElementOf<User[]>; // User
type MyReturnType<F> = F extends (...args: any[]) => infer R ? R : never;
type Unpromise<T> = T extends Promise<infer V> ? Unpromise<V> : T; // like Awaited
type FirstParam<F> = F extends (first: infer P, ...rest: any[]) => any ? P : never;
type Head<T> = T extends [infer H, ...unknown[]] ? H : never; // tuple head
Recursive types
Types can refer to themselves, for data structures and for type-level recursion:
type Json = string | number | boolean | null | Json[] | { [key: string]: Json };
type TreeNode<T> = { value: T; children: TreeNode<T>[] };
type DeepPartial<T> = T extends object ? { [K in keyof T]?: DeepPartial<T[K]> } : T;
type Paths<T> = T extends object // all dotted paths: "user" | "user.address" | "user.address.city"
? { [K in keyof T & string]: K | `${K}.${Paths<T[K]>}` }[keyof T & string]
: never;
Recursion depth is capped, at about 50 levels in general and 1000 for tail-recursive conditional types. Practical advice: type-level programming is powerful but costs readability and compile time. Use it in libraries (form libraries, routers, ORMs such as Prisma and Drizzle), and keep application types simple and explicit.
Modules and declarations
Declaration files
.d.ts files contain only types, describing JavaScript that lives elsewhere: the DOM (lib.dom.d.ts), Node (@types/node), and untyped npm packages (@types/lodash, from DefinitelyTyped). Libraries written in TypeScript ship their own .d.ts generated by tsc --declaration.
// types/legacy-analytics.d.ts — describe a global script you load with <script>
declare global {
interface Window { analytics: { track(event: string, props?: Record<string, unknown>): void } }
}
// describe an untyped module
declare module "tiny-confetti" {
export default function confetti(opts?: { particles?: number }): void;
}
// non-code imports handled by your bundler
declare module "*.svg" { const url: string; export default url; }
export {};
Declaration merging
Declaration merging combines several declarations with the same name into one. It works for interfaces, namespaces, and namespaces with functions, classes or enums. Type aliases can't merge.
interface Box { height: number }
interface Box { width: number } // merged: Box has height and width
Its main practical use is extending types you don't own, which is the next topic.
Module augmentation
Module augmentation adds members to an existing module's types through merging:
// Add a typed custom property to Express's Request
import "express";
declare module "express-serve-static-core" {
interface Request { user?: { id: string; roles: string[] } }
}
// Type your router's metadata (Vue Router), your theme (styled-components/MUI), your env vars:
declare global {
namespace NodeJS { interface ProcessEnv { DATABASE_URL: string; NODE_ENV: "development" | "production" } }
}
Libraries design for this deliberately: Vue Router's RouteMeta, MUI's Theme, TanStack Router's Register interface, and i18next's resources.
Type safety and runtime reality
Compile-time safety isn't runtime validation
compile-time type safety
≠
runtime validation
TypeScript proves your code is consistent with the types you declared. It can't know that the server actually returned what ApiResponse<User[]> claims. Everything crossing a trust boundary arrives as untyped data at run time: fetch responses, JSON.parse, localStorage, URL parameters, form inputs, postMessage, environment variables, and third-party scripts.
const res = await fetch("/api/user/1");
const user = (await res.json()) as User; // ⚠ a LIE the compiler believes: json() returns any
user.email.toLowerCase(); // runtime TypeError if the API sent { mail: "…" } or email: null
The ways TypeScript's guarantees leak:
| Hole | Example |
|---|---|
any |
JSON.parse, res.json(), untyped libraries, catch (e: any) |
| Type assertions | x as User, x! (non-null assertion) |
| Index access | arr[10] is T, not T \| undefined, unless noUncheckedIndexedAccess is on |
| Unsound variance | Covariant mutable arrays, bivariant methods |
Out-of-date .d.ts |
The library changed but its types didn't |
| Version skew | The frontend was deployed against a newer API than the backend actually serving |
Runtime schemas: Zod, Valibot and JSON Schema
Schema validation libraries let you define the shape once as a runtime value, validate data against it, and infer the static type from it, so the type and the check can't drift apart:
import { z } from "zod"; // Zod 4
const User = z.object({
id: z.string().uuid(),
name: z.string().min(1),
email: z.string().email().optional(),
roles: z.array(z.enum(["admin", "editor", "viewer"])).default([]),
createdAt: z.coerce.date(), // parse ISO string → Date
});
type User = z.infer<typeof User>; // the static type, derived from the schema
const parsed = User.safeParse(await res.json());
if (!parsed.success) {
report(parsed.error.issues); // path + message for each problem
throw new Error("Unexpected API response");
}
const user: User = parsed.data; // validated AND typed
import * as v from "valibot"; // modular: small bundles (tree-shakes per function)
const User = v.object({
id: v.pipe(v.string(), v.uuid()),
name: v.pipe(v.string(), v.minLength(1)),
email: v.optional(v.pipe(v.string(), v.email())),
roles: v.optional(v.array(v.picklist(["admin", "editor", "viewer"])), []),
});
type User = v.InferOutput<typeof User>;
const user = v.parse(User, await res.json()); // throws ValiError with issues
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://api.example.com/schemas/user.json",
"type": "object",
"required": ["id", "name"],
"properties": {
"id": { "type": "string", "format": "uuid" },
"name": { "type": "string", "minLength": 1 },
"email": { "type": "string", "format": "email" },
"roles": { "type": "array", "items": { "enum": ["admin", "editor", "viewer"] } }
},
"additionalProperties": false
}
// Spring Boot: Bean Validation on the same contract (Part III)
public record CreateUserRequest(
@NotBlank String name,
@Email String email,
@NotNull List<@Pattern(regexp = "admin|editor|viewer") String> roles) {}
@PostMapping("/users")
ResponseEntity<UserDto> create(@Valid @RequestBody CreateUserRequest body) { … } // 400 on violation
How to choose:
| Zod | Valibot | JSON Schema (+ Ajv) | |
|---|---|---|---|
| Strength | Most popular; huge ecosystem (tRPC, React Hook Form, Next.js and Astro integrations, OpenAI structured outputs) | Smallest bundles; modular functional API | Language-neutral standard: OpenAPI, backend validators in Java/Go/Rust/Python, LLM tool schemas |
| Types | z.infer |
v.InferOutput |
Generate types (json-schema-to-typescript) or use TypeBox |
| Speed | Good (v4 much faster) | Good | Ajv compiles schemas to fast JS functions |
Standard Schema is a small shared interface that Zod, Valibot, ArkType and others implement, so libraries (form libraries, routers, tRPC) can accept any compliant validator.
The architecture that keeps frontend and backend in sync:
- One source of truth for the API contract: an OpenAPI spec (generated from Spring with springdoc, from Go with huma, from Rust with utoipa), a Protobuf or gRPC schema, or shared Zod schemas in a TypeScript monorepo (tRPC).
- Generate the client types and validators from it (openapi-typescript, orval, Kubb). Don't hand-write them.
- Validate at the edges: API responses (at least in development and for critical paths), form input (schema-backed forms), URL search params, and
localStoragereads. - Inside the boundary, trust the types.
This is the "parse, don't validate" principle: convert untyped input into well-typed values once, at the boundary, and let the rest of the code depend on the types.
Lab: what the checker does and doesn't do
Everything below was run with TypeScript 7.0.2, the native Go compiler, and cross-checked with TypeScript 5.9.3 (the messages were identical), plus Node 22.22 (--experimental-strip-types). The experiments map the edges of the type system: where it protects you, and the specific places it can't.
Experiment 1: what strict mode adds
The same file checked with "strict": false and with "strict": true (the default since TypeScript 6.0, so older projects upgrading may meet these errors for the first time):
function findDish(menu, name) {
return menu.find(d => d.name === name);
}
const menu = [{ name: "Dosa", price: 90 }];
const d = findDish(menu, "Idli");
console.log(d.price);
const el = document.getElementById("total");
el.textContent = "₹" + d.price;
function pricePer(qty: number, total?: number) { return total / qty; }
strict off: (no errors, exit 0)
strict on:
loose.ts(1,19): error TS7006: Parameter 'menu' implicitly has an 'any' type.
loose.ts(1,25): error TS7006: Parameter 'name' implicitly has an 'any' type.
loose.ts(2,20): error TS7006: Parameter 'd' implicitly has an 'any' type.
loose.ts(8,1): error TS18047: 'el' is possibly 'null'.
loose.ts(9,57): error TS18048: 'total' is possibly 'undefined'.
Without strict, unannotated parameters silently become any, and null/undefined are allowed everywhere: TypeScript checks almost nothing. strict is a bundle (noImplicitAny, strictNullChecks, strictFunctionTypes, strictBindCallApply, strictPropertyInitialization, useUnknownInCatchVariables, alwaysStrict, and more added over time). Never turn it off, and add noUncheckedIndexedAccess too (it makes arr[i] possibly undefined, which it is). Note that the d.price bug (searching for "Idli" returns undefined) isn't reported yet: menu is any, so d is too. Annotate the parameters and a fourth error appears.
Experiment 2: what the compiler emits
interface Dish { name: string; price: number }
type Veg = Dish & { veg: true };
export function cheapest(menu: readonly Dish[]): Dish | undefined {
return [...menu].sort((a: Dish, b: Dish) => a.price - b.price)[0];
}
export const sizes = ["small", "large"] as const satisfies readonly string[];
enum Spice { Mild, Medium, Hot }
export const level: Spice = Spice.Hot;
export function cheapest(menu) {
return [...menu].sort((a, b) => a.price - b.price)[0];
}
export const sizes = ["small", "large"];
var Spice;
(function (Spice) {
Spice[Spice["Mild"] = 0] = "Mild";
Spice[Spice["Medium"] = 1] = "Medium";
Spice[Spice["Hot"] = 2] = "Hot";
})(Spice || (Spice = {}));
export const level = Spice.Hot;
The interface, the type alias, every annotation, as const and satisfies vanished: they exist only for the checker. The enum didn't: it's one of the few TypeScript features (with namespaces and constructor parameter properties) that generate code. That matters now that runtimes run TypeScript by just deleting the types:
$ tsc --noEmit --erasableSyntaxOnly erase.ts
erase.ts(7,6): error TS1294: This syntax is not allowed when 'erasableSyntaxOnly' is enabled.
$ node --experimental-strip-types erase.ts
SyntaxError [ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX]: TypeScript enum is not supported in strip-only mode
Prefer a union of string literals (type Spice = "mild" | "medium" | "hot") or an as const object over enum, and enable erasableSyntaxOnly (TypeScript 5.8+), so your code runs under Node's type stripping, Deno, Bun and fast transpilers (esbuild, SWC) with no surprises.
Experiment 3: the boundary problem, and a type guard
A server returns {"id": "17", "full_name": "Asha K"} where the frontend expects { id: number; name: string; email: string }:
const raw: unknown = await (await fetch("http://localhost:8030/me")).json();
const trusted = raw as User;
trusted.name.toUpperCase();
trusted.id + 1;
function isUser(x: unknown): x is User {
return typeof x === "object" && x !== null
&& typeof (x as any).id === "number"
&& typeof (x as any).name === "string"
&& typeof (x as any).email === "string";
}
as User → crashed: Cannot read properties of undefined (reading 'toUpperCase')
id + 1 → 171
isUser(raw) → false
The cast compiled and then failed in both directions: a crash on the missing field, and worse, a silently wrong number from the string id. The type predicate x is User is a function the compiler trusts to narrow unknown to User when it returns true; it actually checks. Hand-written guards drift out of sync with types, which is why teams use schema libraries (Zod, Valibot, ArkType) that define the check once and derive the type from it (type User = z.infer<typeof UserSchema>), or generate both from an OpenAPI or JSON Schema contract shared with the backend.
Experiment 4: structural typing, brands, any versus unknown, and exhaustiveness
type Point = { x: number; y: number };
function dist(p: Point) { return Math.hypot(p.x, p.y); }
const p3 = { x: 3, y: 4, z: 12 };
dist(p3); // line 4
dist({ x: 3, y: 4, z: 12 }); // line 5
type Rupees = number & { readonly __brand: "Rupees" };
type Dollars = number & { readonly __brand: "Dollars" };
payInRupees(6 as Dollars); // line 10
const data: any = JSON.parse('{"price":"90"}');
const n: number = data.price; // line 12
const safe: unknown = JSON.parse('{"price":"90"}');
const m: number = safe.price; // line 14
type Status = "placed" | "cooking" | "ready" | "delivered" | "cancelled";
function assertNever(x: never): never { throw new Error("unexpected: " + x); }
switch (s) { /* cases for the first four only */ default: return assertNever(s); } // line 21
structural.ts(5,20): error TS2353: Object literal may only specify known properties, and 'z' does not exist in type 'Point'.
structural.ts(10,13): error TS2345: Argument of type 'Dollars' is not assignable to parameter of type 'Rupees'.
structural.ts(14,19): error TS18046: 'safe' is of type 'unknown'.
structural.ts(21,33): error TS2345: Argument of type '"cancelled"' is not assignable to parameter of type 'never'.
- Line 4 passed, line 5 failed. Types are structural: anything with numeric
xandyis aPoint, extra properties included (dist(p3)printed 5). The excess property check applies only to fresh object literals, where an extra property is almost certainly a typo. Java and C# are nominal (a class is only compatible with what it declares it implements); Go's interfaces are structural like TypeScript's. - Branding restores nominal behaviour where it matters: rupees and dollars are both numbers, but the phantom
__brandmakes them incompatible. anyturns checking off (line 12 compiled, assigning a string to anumber), and spreads: anything derived from ananyisany.unknownis the safe counterpart: you must narrow before use (line 14).JSON.parseandresponse.json()returnany; assign their result tounknown.- Exhaustiveness: when a new status was added to the union, the
assertNeverdefault branch turned the missingcaseinto a compile error. Without it, the function would silently returnundefinedfor cancelled orders.
Try it yourself
- Turn on
noUncheckedIndexedAccessin experiment 1 and fix every new error. Which ones were real bugs? - Replace the hand-written
isUserwith a Zod schema, derive theUsertype from it, and make the fetch function returnPromise<User>only aftersafeParsesucceeds. - Write
type DeepReadonly<T>with mapped and conditional types, then try to modify a nested property. - Type-check a project you work on with TypeScript 5.x and with 7.0 (
npx tsc -p .) and compare the times. On this chapter's tiny files, start-up alone fell from 1.85 s to 0.52 s; on large codebases the gap grows because 7.0 checks files in parallel.
Revision sheet: TypeScript
Key ideas
- TypeScript is a static checker over JavaScript; types are erased. Only
enum,namespaceand parameter properties emit code; avoid them witherasableSyntaxOnly. - Structural typing: compatibility is about shape; excess property checks catch typos in fresh literals; brands add nominal distinctions.
- Inference flows from values and context; annotate parameters, exported APIs and data models.
- Unions + narrowing (
typeof,instanceof,in, equality, discriminant fields, type predicates, assertion functions); exhaustiveness withnever. - Generics with constraints (
<T extends { id: string }>), defaults and inference; variance (in/outannotations) matters for function types. - Type-level tools:
keyof, indexed accessT[K], mapped types, conditional types withinfer, template literal types, utility types (Partial,Pick,Omit,Record,ReturnType,Awaited). satisfieschecks a value against a type without widening it;as constkeeps literal types.- Unsound escapes:
any,as, non-null!, overloads, bivariant method parameters, index access withoutnoUncheckedIndexedAccess. - Boundaries: validate external data at run time (schemas) and derive types from the schema or a shared contract.
- Declarations:
.d.tsfiles,@types/*, module augmentation and declaration merging; module resolutionbundlervsnodenext.
Numbers to remember
strictbundles about eight checks and is the default since TypeScript 6.0; addnoUncheckedIndexedAccessandexactOptionalPropertyTypesdeliberately.- TypeScript 7.0 (2026) is the native Go compiler, reported at around 10× faster on large projects; 6.0 was the last JavaScript-based release.
- Node runs
.tswith type stripping (flag in 22, default from 23.6).
Pitfalls
ason API responses;anyfromJSON.parseleaking through the app.- Non-null assertions (
el!) instead of handling the null case. enumwith type stripping; numeric enums accepting any number.- Optional properties vs
| undefined(they differ underexactOptionalPropertyTypes). - Over-engineered type-level code that slows the checker and confuses readers.
- Assuming
readonlyor private (privatekeyword) is enforced at run time; use#privatefor that.
Glossary
- Assignability: whether a value of one type may be used where another is expected.
- Type predicate: a return type
x is Tthat narrows when the function returns true. - Discriminant: the literal-typed property that tells union members apart.
- Widening: inference choosing
stringinstead of"ready"for mutable bindings. - Declaration file: a
.d.tsfile describing types for JavaScript code. - Type stripping: running TypeScript by deleting type syntax without checking it.