Generics, narrowing, utility and conditional types, tsconfig. Open a question to read the answer.
Both declare a named shape, and for a plain object both compile to nothing at runtime. The differences are in what each can express and how it behaves when redeclared.
| Aspect | interface | type | alias |
|---|---|---|---|
| Can describe | Object shapes, call/construct signatures | Anything: unions, tuples, primitives, mapped and conditional types | |
| Extension | extends another interface or object type | Intersection with | & |
| Declaration merging | Yes, same-name declarations merge | No, duplicate names are an error | |
| Error messages | Shows the interface name | Often expands to the full structural shape | |
implements by a class | Yes | Yes, if the alias resolves to an object type |
interface User { id: string; name: string }
interface User { email?: string } // merges into the same User
type Status = "active" | "suspended"; // not expressible as an interface
type AdminUser = User & { role: "admin" }; // intersection instead of extendsInterfaces are checked slightly more lazily and cache their members, which the TypeScript team cites as a performance reason to prefer them for object shapes in large codebases. A reasonable house rule is “interface for object contracts, type for everything else”.
Apply. In an order service I use interfaces for public contracts that other teams extend: OrderRepository, PaymentGateway, DTOs exposed from a shared package. Declaration merging is deliberately used to augment third-party types, for example adding user to Express’s Request in a declarations.d.ts. Type aliases are reserved for unions (OrderState), tuples, derived shapes (Pick<Order, "id" | "total">), and template-literal types for event names. An ESLint rule (@typescript-eslint/consistent-type-definitions) enforces the choice automatically so it never becomes a code-review debate.
Test. Type-level behaviour is tested with expectTypeOf from Vitest or tsd: assert that AdminUser is assignable to User, and that an invalid state string fails with // @ts-expect-error. Those assertions run in the normal tsc --noEmit step, so a refactor that silently widens a contract breaks CI.
Troubleshoot. The classic symptom is an accidental merge: two developers declare interface Config in different files of the same global script context and get a confusing union of properties. The fix is to make the files modules (add an export) or switch to a type alias so the duplicate becomes a hard error. Another is an unreadable hover showing a huge expanded alias; converting that alias to an interface restores the readable name.
The important consideration is that neither choice exists at runtime, so a decision between them never affects bundle size or behaviour, only ergonomics and tooling.
These are the three ends of TypeScript’s type lattice: any and unknown are top types that accept every value, and never is the bottom type that accepts none.
any opts out of checking. Any value is assignable to it and it is assignable to anything, so a single any can silently spread unsafety through a codebase.unknown also accepts every value, but nothing can be done with it until it is narrowed with typeof, instanceof, a type guard or a schema check. It is the type-safe way to say “I do not know yet”.never is the type of values that cannot occur: a function that always throws, an exhausted union branch, or an impossible intersection such as string & number. It is assignable to every type and nothing except never is assignable to it.function fail(msg: string): never { throw new Error(msg); }
function size(input: unknown): number {
if (typeof input === "string") return input.length; // narrowed
if (Array.isArray(input)) return input.length;
return fail("unsupported"); // returns never
}Since TypeScript 4.4, catch clause variables default to unknown under useUnknownInCatchVariables (part of strict), which is the most common place developers meet it.
Apply. In a payments pipeline, everything that crosses a trust boundary arrives as unknown: JSON.parse results, req.body, webhook payloads, catch (err). A parse function narrows it to a concrete type before any business logic runs. never is used for exhaustiveness: the default branch of a switch over PaymentEvent["type"] assigns the value to a never variable, so adding a new event type breaks compilation until every handler is updated. any is confined to generated code and a few typed-escape wrappers, enforced by @typescript-eslint/no-explicit-any and noImplicitAny.
Test. Type tests assert that a value of type unknown cannot be passed to a function expecting Payment (// @ts-expect-error). A unit test feeds malformed webhook JSON through the narrowing function and expects a rejection rather than a thrown TypeError deeper in the stack. The exhaustiveness check is itself a compile-time test; CI runs tsc --noEmit separately from the bundler because esbuild and swc strip types without checking them.
Troubleshoot. A frequent symptom is “property does not exist on type unknown” after enabling strict, usually on err.message in a catch block; the fix is err instanceof Error ? err.message : String(err). The opposite problem is a runtime crash with no compile error, traced back with --noImplicitAny reports or ts-prune -style audits to an any leaking from an untyped library.
The important consideration is that any is contagious: one any returned from a helper makes every downstream property access unchecked.
A union A | B is a value that is either an A or a B; an intersection A & B is a value that is both at once, so it must satisfy every member’s requirements.
(string | number).toUpperCase() is an error; after typeof x === "string" it compiles.{ id: string } & { id: number } makes id of type never.type Timestamped = { createdAt: Date };
type SoftDeletable = { deletedAt: Date | null };
type Account = { id: string; owner: string } & Timestamped & SoftDeletable;
type SearchKey = string | number | { id: string };
function find(key: SearchKey) {
if (typeof key === "object") return key.id; // narrowed to { id: string }
return String(key);
}Set-theoretically, a union is bigger (more values fit) and an intersection is smaller (fewer values fit), which is why string & number collapses to never.
Apply. In a notification service the delivery channel is a union: EmailMessage | SmsMessage | PushMessage, each with its own required fields. Intersections compose cross-cutting metadata (& Traceable & Tenanted) onto request types without creating an inheritance tree. Function parameters accept the widest sensible union (string | URL) while return types stay narrow, which keeps call sites flexible and consumers precise.
Test. Type tests verify assignability in both directions: EmailMessage is assignable to the union, the union is not assignable to EmailMessage, and an intersection with conflicting keys resolves to never where that is the intent. Runtime tests use table-driven cases, one per union member, so coverage tools show every branch of the dispatch exercised.
Troubleshoot. The symptom “Property ‘subject’ does not exist on type EmailMessage | SmsMessage ” means a developer used a member-specific field before narrowing; the fix is a discriminant check or a type guard, never a cast. A subtler issue is an intersection that became never because two mixins both declared id with different types, and every assignment to it now fails with a baffling message. Hovering the type in the editor or extracting it with type Debug = Account["id"] reveals the never. Long unions of large object types can also slow type checking; tsc --extendedDiagnostics shows check time, and splitting the union or adding a discriminant restores speed.
The important consideration is that an intersection of object types is additive, but an intersection of primitives or conflicting literals silently produces never.
Generics let a function, class or type take type parameters so one implementation works across many types while preserving the relationship between inputs and outputs. A constraint (T extends Something) limits which types may be supplied, which in turn tells the compiler what operations are legal on T inside the body.
function pluck<T, K extends keyof T>(items: T[], key: K): T[K][] {
return items.map(item => item[key]);
}
const users = [{ id: 1, name: "Ana" }, { id: 2, name: "Bo" }];
const names = pluck(users, "name"); // string[]
pluck(users, "email"); // error: "email" is not a key of TKey points:
<T> is needed only when nothing in the arguments pins them down.K extends keyof T forces K to be a literal key of T, not just any string.<T = string>) make a parameter optional for callers.new T() or typeof T at runtime is impossible without passing a constructor as a value.Over-generic code is a common smell: if a type parameter is used only once, a plain unknown or concrete type is usually clearer.
Apply. A typical production use is a repository layer: interface Repository<T extends { id: string }> with findById(id: string): Promise<T | null>, implemented once over Prisma or Knex and specialised for Order, Customer, Invoice. The constraint guarantees every entity has an id, so the generic code can read it. Another is a typed event bus, emit<K extends keyof Events>(name: K, payload: Events[K]), where the constraint ties the payload type to the event name. Response wrappers (ApiResult<T>) and typed fetch helpers round it out.
Test. Type tests assert inference: expectTypeOf(repo.findById("x")).resolves.toEqualTypeOf<Order | null>(), and // @ts-expect-error guards that emit("orderPaid", { wrongField: 1 }) fails. Runtime tests cover the implementation once with a simple entity, because the type parameter adds no runtime behaviour to test.
Troubleshoot. The most common error is “Type ‘T’ is not assignable to type ‘X’” inside a generic body, which almost always means the constraint is too weak for what the code does; strengthening the constraint, not casting, is the fix. Inference failures where a parameter resolves to unknown are usually caused by the generic appearing only in a callback’s return position; adding an explicit type argument at the call site or reordering parameters helps. Slow compilation from deeply recursive generics is diagnosed with tsc --generateTrace and resolved by simplifying or capping recursion.
The important consideration is that a type parameter erased at runtime cannot be used to drive behaviour, so “generic” serialisers still need a runtime schema or constructor argument.
Type inference is the compiler working out a type from context so the developer does not have to write it. Initialisers, return statements, array literals and generic call arguments are all inferred; contextual typing flows the other way, from an expected type into a callback’s parameters.
let count = 10; // number
const limit = 10; // literal 10 (const keeps the literal)
const ids = [1, 2, 3]; // number[]
const pair = [1, "a"] as const; // readonly [1, "a"]
function area(w: number, h: number) { return w * h; } // return: number
[1, 2, 3].map(n => n * 2); // n inferred as number from map's signatureRules that matter in practice:
let widens literals ("x" becomes string); const keeps them.[1, "a"] infers (string | number)[].any (an error under noImplicitAny) or a generic parameter falls back to unknown.Since TypeScript 5.x, const type parameters (function f<const T>(x: T)) let a generic infer literal types as if the caller had written as const.
Apply. In a reporting warehouse’s ingestion code, inference is relied on for locals and callbacks and deliberately overridden at module boundaries: every exported function gets an explicit return type, and every public object literal is annotated or passed through satisfies so typos are caught without losing the inferred literal types. Configuration objects use as const so inferred keys drive downstream types, for example type ReportName = keyof typeof reports. Libraries such as Zod and tRPC are chosen partly because they infer end-to-end types from a single definition instead of asking for duplicates.
Test. expectTypeOf(buildReport(cfg)).toEqualTypeOf<Report>() style assertions pin inferred types that other code depends on. A CI step runs tsc --noEmit with noImplicitAny so any place inference silently fell back to any fails the build.
Troubleshoot. Typical symptoms: a value inferred as string where a literal "daily" was expected (fix: as const or a const type parameter), an array inferred as never[] because it was initialised empty (fix: annotate const rows: Row[] = []), or a union widened to (A | B)[] where a tuple was intended. Declaration emit errors like “return type cannot be named” come from inferred types referencing non-exported types; an explicit annotation resolves them. Slow editor feedback in large files is often inference over huge literals, which --extendedDiagnostics confirms.
The important consideration is that inferred types change when the implementation changes, so relying on inference for a public API means a refactor can silently alter the contract.
Narrowing is the compiler refining a variable’s type inside a branch based on a runtime check, and a type guard is any expression it understands as such a check. Because types are erased, the check itself must be ordinary JavaScript that runs; the compiler merely tracks what each branch proves.
Built-in guards:
typeof x === "string" for primitives.x instanceof Date for classes."id" in x for property presence.x.kind === "circle"), truthiness, and Array.isArray.if (!x) return;, x is non-nullable.Custom guards are functions whose return type is a type predicate.
interface Cat { meow(): void }
interface Dog { bark(): void }
function isCat(pet: Cat | Dog): pet is Cat {
return "meow" in pet;
}
function speak(pet: Cat | Dog) {
if (isCat(pet)) pet.meow(); // Cat
else pet.bark(); // Dog
}Assertion functions (asserts value is User) narrow after a call that throws on failure. TypeScript 5.5 added inferred type predicates: a function such as (x): boolean => typeof x === "string" is now recognised as a guard without an explicit x is string annotation.
Apply. In a CI pipeline runner I model job results as a union and write guards at the boundaries where untyped data enters: isJobEvent(raw: unknown): raw is JobEvent wraps a schema check so that one function both validates at runtime and narrows for the compiler. Assertion functions (assertDefined(value, "job id")) replace scattered if (!x) throw blocks. Filtering uses .filter(isSuccess) so the result is SuccessResult[] rather than the original union.
Test. Each guard gets table-driven unit tests with valid and invalid inputs, because a guard with a bug is worse than no guard: the compiler trusts the predicate completely. Type tests confirm the narrowing, for example that inside if (isSuccess(r)) the property r.artifactUrl is a string.
Troubleshoot. The common complaint is “narrowing does not stick”: a check on obj.kind followed by a callback, an await, or a property access through a function call loses the narrowing because TypeScript cannot prove the value did not change. The fix is to copy the value into a const before checking, or to narrow inside the callback. Another is a guard that lies, such as isUser(x): x is User that only checks typeof x === "object"; a downstream undefined is not a function crash traces back to it. Running the guard tests with a fuzzer such as fast-check catches those cheaply.
The important consideration is that a type predicate is a promise to the compiler, not something it verifies, so guard bodies deserve the same review rigour as security checks.
A discriminated union is a union of object types that share one property with a distinct literal value in each member, called the discriminant or tag. Checking that property narrows the whole object to the matching member, which gives type-safe variants without classes or inheritance.
type PaymentEvent =
| { type: "authorized"; amount: number; authCode: string }
| { type: "captured"; amount: number; capturedAt: Date }
| { type: "failed"; reason: string };
function describe(e: PaymentEvent): string {
switch (e.type) {
case "authorized": return `auth ${e.authCode}`;
case "captured": return `captured ${e.amount}`;
case "failed": return `failed: ${e.reason}`;
default: {
const exhaustive: never = e; // compile error if a case is missing
return exhaustive;
}
}
}Why they are preferred over optional fields on one big type:
authCode) cannot be represented.never turns “forgot a case” into a compile error.The discriminant must be a literal type (string, number, boolean or enum member); a string -typed type field will not narrow. This mirrors algebraic data types in Rust, Haskell and F#.
Apply. Order lifecycle state is the textbook case: Draft, Placed, Paid, Shipped, Cancelled, each carrying only the data that exists in that state (paidAt only on Paid, trackingId only on Shipped). Transitions are functions from one member to another, so an attempt to ship a Draft is a compile error rather than a runtime guard. The same pattern types API responses ({ ok: true; data } | { ok: false; error }), Redux-style actions, and message-queue envelopes. This diagram shows the state machine the union encodes.

Test. Exhaustiveness is tested by the compiler through the never default branch; a unit test per transition checks the produced member and that invalid transitions throw at runtime for data arriving from outside. Serialisation round-trips (JSON.parse(JSON.stringify(order))) are run through the schema validator to confirm the tag survives.
Troubleshoot. When narrowing fails on switch (order.status), the usual causes are a discriminant typed as string instead of literals, or the object destructured before the check (const { status, trackingId } = order loses the link between the two). Keeping the object intact until after the check, or using TypeScript 4.6+ destructured discriminant narrowing with const declarations, fixes it. A never branch that refuses to compile after adding a state is the feature working as intended.
The important consideration is that the tag must be a literal type and every member must have it; one member without the discriminant disables narrowing for the whole union.
These are built-in mapped types that derive a new object type from an existing one, so related shapes stay in sync with a single source definition.
| Utility | Produces | Typical use |
|---|---|---|
Partial<T> | Every property optional | Update payloads, default-merged options |
Required<T> | Every property required | Config after defaults are applied |
Pick<T, K> | Only the listed keys | Projections, list-view DTOs |
Omit<T, K> | Everything except the listed keys | Creation input without id /timestamps |
Readonly<T> | Every property readonly | Frozen state, props |
interface Product {
id: string; sku: string; name: string; price: number; createdAt: Date;
}
type NewProduct = Omit<Product, "id" | "createdAt">;
type ProductPatch = Partial<Pick<Product, "name" | "price">>;
type ProductSummary = Pick<Product, "id" | "name">;Partial is shallow: nested objects stay fully required unless a recursive DeepPartial is written. Pick constrains K extends keyof T, so a misspelt key is an error, whereas Omit is defined as Pick<T, Exclude<keyof T, K>> with K extends keyof any, so it silently accepts keys that do not exist. Record<K, V>, Exclude, Extract, NonNullable, ReturnType and Awaited belong to the same family.
Apply. In a catalogue service the database row type is the single source of truth. Omit<ProductRow, "id" | "createdAt" | "updatedAt"> is the insert type, Partial<Omit<ProductRow, "id">> is the PATCH body, and Pick<ProductRow, "id" | "name" | "price"> is the list-endpoint projection. Repository methods are typed against those derived types so a column added to the row flows to every DTO automatically. For the public API package we export the derived types with names, never the raw utility expressions, so consumers see ProductPatch rather than a nested Partial<Omit<...>> in hovers.
Test. Type tests assert that ProductPatch has no id key and that every key is optional (expectTypeOf<ProductPatch>().toMatchTypeOf<{ name?: string }>()). Integration tests send a PATCH with an unexpected id field and confirm the runtime schema rejects it, because Omit removes the key from the type but does nothing to the incoming JSON.
Troubleshoot. A rename of price to unitPrice breaks Pick<Product, "price"> loudly, which is good, but Omit<Product, "price"> keeps compiling and now exposes unitPrice on the insert type; a stricter StrictOmit<T, K extends keyof T> alias solves it. Another symptom is Partial making a required nested object optional only at the top level, so code does patch.address.city without checking address; a DeepPartial or explicit narrowing fixes it. Confusing errors mentioning Pick<Pick<...>> are cleaned up by introducing named intermediate aliases.
The important consideration is that these types shape compile-time contracts only; the matching runtime validation must be derived or kept in sync separately.
A mapped type builds a new object type by iterating over a set of keys, usually keyof some existing type, and declaring a property for each. The in keyword drives the iteration, and modifiers (?, readonly, with + or -) can be added or removed per property. Partial, Required, Readonly and Record are all mapped types in lib.d.ts.
type Getters<T> = {
[K in keyof T as `get${Capitalize<string & K>}`]: () => T[K];
};
type Nullable<T> = { [K in keyof T]: T[K] | null };
type Mutable<T> = { -readonly [K in keyof T]: T[K] };
interface Point { readonly x: number; readonly y: number }
type PointGetters = Getters<Point>; // { getX: () => number; getY: () => number }
type Draft = Mutable<Point>; // { x: number; y: number }Key behaviours:
[K in keyof T]) preserve the original optional and readonly modifiers unless explicitly changed.as (TypeScript 4.1+) can rename or filter keys; mapping a key to never drops it.keyof, produces a fresh object type, which is how Record<"a" | "b", number> works.Readonly<[number, string]> is a readonly tuple.They are evaluated once per instantiation and entirely erased, so they cost nothing at runtime.
Apply. In a form-heavy admin application a single FormValues type drives several derived shapes: Errors<T> = { [K in keyof T]?: string }, Touched<T> = { [K in keyof T]: boolean }, and a Validators<T> map of per-field functions. Adding a field to the form type immediately demands a validator and error slot everywhere. On the backend, a mapped type over an event-name union generates the handler registry type, { [E in EventName]: (payload: EventPayload[E]) => Promise<void> }, so a missing handler fails compilation. Key remapping converts snake_case database columns to camelCase API fields at the type level, mirroring the runtime mapper.
Test. Type tests assert the produced shape with toEqualTypeOf, including that modifiers survive: a required field stays required, an optional one stays optional. The runtime mapper that corresponds to the type-level remap is tested with a fixture row, and a type test confirms the mapper’s return type equals the remapped type so the two cannot drift.
Troubleshoot. The most common bug is the mapped type widening unexpectedly when the input is a union; keyof (A | B) is only the shared keys, so the fix is a distributive conditional wrapper. Another is losing modifiers because the map iterates over keyof T indirectly through a type parameter constraint rather than directly, which makes it non-homomorphic. Deep recursive mapped types can hit “Type instantiation is excessively deep”; capping depth or using an interface for the recursive step resolves it. Hovering an intermediate alias or using a Prettify<T> helper makes the expanded result readable.
The important consideration is that mapped types compute compile-time shapes only, so each one needs a matching runtime function if the transformation must also happen to data.
A conditional type chooses between two types based on an assignability test: T extends U ? X : Y. Combined with infer it can pull types out of other types, which is how ReturnType, Parameters, Awaited and Extract are implemented in the standard library.
type ElementOf<T> = T extends readonly (infer E)[] ? E : never;
type Unwrap<T> = T extends Promise<infer V> ? Unwrap<V> : T;
type A = ElementOf<string[]>; // string
type B = Unwrap<Promise<Promise<number>>>; // number
type ApiResponse<T> = T extends { error: string } ? { ok: false } & T
: { ok: true; data: T };Two rules account for most surprises:
Exclude<"a" | "b", "a"> is "b" for this reason. Wrapping both sides in a tuple ([T] extends [U]) disables distribution.T is known, so the type stays unresolved and the body may need a cast or an overload.infer can carry its own constraint since TypeScript 4.7 (infer S extends string), which avoids a second conditional. Conditional types are evaluated by the checker and erased from output; they influence only which types are accepted.
Apply. In an internal SDK for a REST API, conditional types derive the response type from the route: type ResponseOf<R extends Route> = R extends { method: "GET"; path: infer P } ? GetResponses[P] : never. A typed fetch wrapper then returns Promise<ResponseOf<R>> without hand-written per-endpoint signatures. Another everyday use is Awaited -style unwrapping of a repository method’s return type for tests, and Extract<Event, { type: "payment.*" }> -style filtering of a large union using template-literal patterns.
Test. Conditional types are tested purely at the type level: expectTypeOf<ResponseOf<GetOrder>>().toEqualTypeOf<Order>(), with cases for the distributive and non-distributive paths and for a union input. A deliberate // @ts-expect-error confirms that a POST route does not resolve to a GET response. These files are part of the tsc --noEmit run in CI so they fail the build, not just the editor.
Troubleshoot. When a result is unexpectedly a union, the conditional distributed over a union input; wrapping in [T] extends [U] fixes it. When it is unexpectedly never, the inverse happened or a constraint excluded every member. “Type instantiation is excessively deep and possibly infinite” appears with recursive conditionals over long tuples; TypeScript 4.5 raised the tail-recursion limit to roughly 1000 for conditionals in tail position, so restructuring the recursion to be tail-recursive usually resolves it. Slow editor response is diagnosed with tsc --generateTrace and the @typescript/analyze-trace tool, which pinpoints the expensive instantiation.
The important consideration is readability: a conditional type that takes a minute to understand belongs behind a well-named alias with a type test, or should be replaced by overloads.
keyof T is a type operator that produces the union of property names of T. typeof x in a type position captures the static type of a value, which is distinct from the runtime JavaScript typeof that returns a string. Together they let types be derived from existing values rather than duplicated by hand.
const routes = {
home: "/",
orders: "/orders",
orderDetail: "/orders/:id",
} as const;
type Routes = typeof routes; // { readonly home: "/"; ... }
type RouteName = keyof Routes; // "home" | "orders" | "orderDetail"
type RoutePath = Routes[RouteName]; // "/" | "/orders" | "/orders/:id"
function go(name: RouteName) { location.assign(routes[name]); }
go("orders"); // ok
go("profile"); // errorPoints worth knowing:
keyof of a type with a string index signature is string | number; keyof any is string | number | symbol.keyof on an object type returns only known keys, including optional ones; mapped types rely on this.typeof works on variables, properties, functions and class instances, but not on arbitrary expressions; typeof fn() is invalid.ReturnType<typeof fn> is the standard way to name an inferred return type without exporting it.Apply. Configuration-driven code is where these pay off. In a feature-flag module a single as const object of flag definitions is the source of truth; keyof typeof flags types every call to isEnabled(flagName), and typeof flags[K]["default"] types the return. Environment variable loading uses keyof typeof schema so a typo in process.env access fails to compile. Generic helpers such as groupBy<T, K extends keyof T>(items: T[], key: K) use keyof constraints to limit keys to real properties. The flow is shown below.
Test. Type tests assert FlagName equals the expected literal union and that adding a flag to the object extends it automatically. A // @ts-expect-error on isEnabled("not-a-flag") ensures the constraint holds. Runtime tests only cover the lookup function, since keyof and typeof produce no runtime code.
Troubleshoot. The most frequent symptom is keyof typeof obj resolving to string because the object had an index signature or was typed as Record<string, ...>; removing the annotation and using satisfies restores literal keys. Developers also confuse the two typeofs and write if (typeof x === SomeType), which fails because the right-hand side is a type. “Element implicitly has an ‘any’ type because expression of type ‘string’ can’t be used to index” means a loop variable typed string indexes an object; narrowing to keyof typeof obj or using Object.entries with a typed helper fixes it.
The important consideration is that typeof in a type position reads the declared type, so widening (let x = "a" giving string) propagates into everything derived from it.
A literal type is a type with exactly one value: "GET", 42, true, or a template-literal pattern such as `order:${string}`. Unions of literals model closed sets of allowed values, and as const is the assertion that tells the compiler to infer the narrowest literal types for an expression and make it deeply readonly.
const method = "GET"; // type "GET" (const binding keeps the literal)
let verb = "GET"; // type string (let widens)
const config = { retries: 3, mode: "fast" };
// { retries: number; mode: string }
const frozen = { retries: 3, mode: "fast" } as const;
// { readonly retries: 3; readonly mode: "fast" }
const LEVELS = ["debug", "info", "error"] as const;
type Level = (typeof LEVELS)[number]; // "debug" | "info" | "error"Why the pattern matters:
as const a mode: "fast" cannot be passed where "fast" | "slow" is required.as const on an array produces a readonly tuple, which makes (typeof arr)[number] a precise union, a common replacement for enums.`${Entity}Created` from an Entity union.satisfies (4.9+) checks a literal against a type while preserving the inferred literal types, which as const alone does not validate.Nothing is emitted for as const; it is a pure type assertion, and the readonly-ness is not enforced by Object.freeze at runtime.
Apply. In an event-driven order system every event name, HTTP method, queue name and role is a literal union derived from an as const array that also serves as the runtime list for validation and documentation, so there is a single definition rather than an enum plus a parallel string array. Route tables, i18n keys and analytics event names use the same pattern with template-literal types producing `${Entity}.${Action}` names. satisfies guards configuration objects so a typo in a key is caught while literal values remain precise for downstream keyof.
Test. Type tests confirm Level is the expected union and that LEVELS.includes(x) can act as a guard via a small isLevel helper. Runtime tests check the validator built from the array rejects unknown strings, and a schema test ensures the OpenAPI document lists the same enum values as the array, since the type system cannot check documentation.
Troubleshoot. The usual error is “Argument of type ‘string’ is not assignable to parameter of type ‘“GET” | “POST”’” when a value came from a let, a function return typed string, or a non-const object; moving as const to the source, or narrowing with a guard, fixes it. The inverse problem is over-narrowing: as const on a mutable config object makes config.retries = 5 an error, so the assertion belongs only on true constants. Developers also expect as const to prevent runtime mutation; it does not, and Object.freeze is needed where that matters. readonly string[] not being assignable to string[] after as const is fixed by accepting readonly arrays in function parameters.
The important consideration is that as const changes only the inferred type, never the emitted JavaScript or the object’s runtime mutability.
Optional chaining (?.) and nullish coalescing (??) are ECMAScript 2020 operators that TypeScript supported from version 3.7 and down-levels for older targets. They are about null and undefined specifically, not general falsiness.
a?.b evaluates to undefined if a is null or undefined, otherwise a.b. It short-circuits the rest of the chain, so a?.b.c() does not evaluate .c() when a is nullish. Variants: a?.[key] and fn?.().x ?? fallback returns fallback only when x is null or undefined. Unlike ||, it keeps 0, "" and false.??= (ES2021) assigns only when the target is nullish.interface Order {
customer?: { address?: { postcode?: string } };
discount?: number;
}
function label(order: Order) {
const postcode = order.customer?.address?.postcode ?? "unknown";
const discount = order.discount ?? 10; // 0 stays 0; `|| 10` would give 10
return `${postcode} ${discount}`;
}Under strictNullChecks the type system tracks these precisely: order.customer?.address has type { postcode?: string } | undefined, and the ?? result drops undefined. For targets below ES2020 the compiler emits the equivalent === null || === void 0 checks; with ES2020 or later the operators pass through unchanged.
Apply. In a storefront that renders partial API responses, ?. is used at genuinely optional nesting points such as order.shipping?.eta and ?? supplies domain defaults such as quantity ?? 1. The team’s rule is that ?. is justified only where the type says the value may be nullish; it is not sprinkled defensively over values the types guarantee, because that hides modelling errors. Event handler props use onSelect?.(item) instead of if (onSelect) onSelect(item). Lint rules @typescript-eslint/prefer-nullish-coalescing and prefer-optional-chain enforce the style automatically.
Test. Unit tests include the falsy-but-not-nullish cases explicitly: a discount of 0, an empty-string note, and false flags, asserting they are preserved by ??. A snapshot test renders a component with the minimal valid payload (every optional field absent) to exercise each chain’s short-circuit path.
Troubleshoot. The classic regression is replacing || with ?? mechanically and changing behaviour for empty strings; a code search for ?? "" versus || "" and a review of intent resolves it. “Unnecessary optional chain” lint warnings reveal places where the type was wrong or where ?. is masking a real bug such as a missing await. If a build for an old target suddenly fails in a legacy browser, the operators were emitted untranspiled because a bundler bypassed tsc; aligning the bundler’s target with tsconfig fixes it. Mixing ?? with || or && without parentheses is a syntax error by design, which prompts clarifying the intended precedence.
The important consideration is that ?. swallows nullish values silently, so an unexpected undefined deep in a chain surfaces far from its cause unless logged or validated at the boundary.
strictNullChecks is the compiler option that removes null and undefined from every type unless they are explicitly included. With it off, null is assignable to string, Order, or anything else, which reproduces the “cannot read properties of undefined” class of runtime bugs that TypeScript is meant to prevent. It is part of the strict family and has been the recommended default since it shipped in TypeScript 2.0.
function findUser(id: string): User | undefined { /* ... */ }
const user = findUser("42");
user.name; // error: 'user' is possibly 'undefined'
user?.name; // ok: string | undefined
if (user) user.name; // ok: narrowed to User
const el = document.getElementById("app"); // HTMLElement | null
el!.focus(); // non-null assertion: compiles, may throw at runtimeWhat changes when it is on:
Array.prototype.find returns T | undefined, Map.get returns V | undefined, DOM queries return | null.x?: T) are read as T | undefined; exactOptionalPropertyTypes (4.4+) can additionally forbid assigning undefined explicitly.let declarations used before assignment.The option affects only type checking; emitted JavaScript is identical with it on or off.
Apply. Every new service starts with "strict": true. When enabling it on an existing codebase, the practical approach is incremental: turn it on in tsconfig, capture the error count, and either fix module by module or use a tool such as typescript-strict-plugin or ts-strictify that allows per-file opt-in while the rest is fixed. Repository methods return T | null rather than throwing for not-found, and HTTP handlers narrow once at the top (if (!order) return reply.code(404)), so the rest of the handler works with a definite Order. Non-null assertions (!) are banned by lint outside test files.
Test. Unit tests cover the “absent” branch of every nullable return: missing user, empty query, header not present. Type tests assert that repo.find() returns Order | null, so a refactor to a throwing implementation must update the type and the callers together. CI runs tsc --noEmit because Vite, esbuild and swc do not perform this checking.
Troubleshoot. After enabling the option, the largest error cluster is usually “Object is possibly ‘undefined’” on array[i] and map.get(); fixes are a guard, a default via ??, or noUncheckedIndexedAccess left off until later. “Property has no initializer and is not definitely assigned” on class fields is solved by initialising in the declaration, using ! with a comment when a framework injects it, or making the type | undefined. A production TypeError despite strict mode almost always traces to a ! assertion, an as cast, or data entering untyped from JSON.parse; searching for !. and auditing boundary parsing locates it.
The important consideration is that the option cannot see runtime data, so it only pays off fully when API responses and environment variables are validated before they are given a non-nullable type.
readonly is a compile-time modifier that forbids reassignment of a property, index or array element after construction. It has no runtime effect: the emitted JavaScript contains ordinary mutable objects, and a cast or an untyped caller can still mutate them. Runtime immutability requires Object.freeze or immutable data structures.
Forms it takes:
readonly id: string in an interface or class; assignable only in the declaration or constructor.readonly string[] / ReadonlyArray<string> and readonly [number, number] remove push, splice and index assignment.Readonly<T> is shallow; ReadonlyMap, ReadonlySet exist for collections.as const makes a literal deeply readonly.interface Money { readonly amount: number; readonly currency: string }
function applyFee(m: Money): Money {
// m.amount += 1; // error: cannot assign to 'amount'
return { ...m, amount: m.amount + 1 }; // return a new value instead
}
const prices: readonly number[] = [10, 20];
prices.push(30); // error: push does not exist
const copy = [...prices, 30]; // fineA mutable string[] is assignable to readonly string[] but not the reverse, so accepting readonly arrays in parameters is the more permissive signature. readonly properties are not checked for assignability differences between types: { readonly x: number } and { x: number } are mutually assignable, which is a known soundness gap.
Apply. In a React and Redux front end, state and props types are declared Readonly or built with as const, and reducers return new objects via spread or Immer, so accidental mutation of shared state becomes a compile error. On the backend, domain value objects such as Money and DateRange have readonly fields and methods that return new instances, which makes them safe to cache and share across requests. Function parameters are typed readonly T[] by default so callers can pass either mutable or frozen arrays. Object.freeze is applied to module-level configuration once at startup because that object crosses into untyped plugin code.
Test. Unit tests for reducers and value objects assert referential inequality (expect(next).not.toBe(prev)) and that the input is unchanged (toEqual against a deep clone taken before the call). Type tests confirm that state.items.push is an error. For code that must mutate, tests run with Object.freeze applied to fixtures so any attempt throws in strict-mode JavaScript.
Troubleshoot. The telltale production symptom is a stale UI or a cache returning altered data because one code path mutated an object the types said was readonly; the path is almost always a cast, an any, or a library like lodash.merge operating on the original. Freezing fixtures in tests reproduces it as a TypeError. Compile errors “readonly string[] is not assignable to string[]” on third-party calls are resolved by copying with spread rather than casting. The @typescript-eslint/prefer-readonly and prefer-readonly-parameter-types rules help find missed spots, though the latter is noisy.
The important consideration is that readonly is erased, so it documents and enforces intent for TypeScript callers only; anything untyped can still mutate the data.
Function overloads let one function declare several call signatures so callers get a precise return type depending on the argument types they pass. TypeScript has no runtime dispatch: there is one implementation, and its body must check the arguments itself. The overload signatures are erased; only the implementation is emitted.
function parse(input: string): number;
function parse(input: string[]): number[];
function parse(input: string | string[]): number | number[] {
return Array.isArray(input) ? input.map(Number) : Number(input);
}
const one = parse("1"); // number
const many = parse(["1", "2"]); // number[]
parse(42); // error: no overload matchesRules that matter:
lib.d.ts uses them heavily (document.createElement("div") returning HTMLDivElement).Union parameters are preferred when the return type does not depend on the argument; overloads earn their place when it does.
Apply. In a shared HTTP client, request is overloaded so request("GET", "/orders") returns Promise<Order[]> and request("POST", "/orders", body) returns Promise<Order>, with the body parameter required only on the mutating overload. An event emitter’s on(event, handler) is overloaded per event name so handler payloads are typed. A database helper query(sql) returning Row[] and query(sql, { single: true }) returning Row | null is a third common shape. When the mapping grows beyond a handful of signatures, overloads are replaced by a generic indexed into an event or route map, which scales better.
Test. Type tests assert each overload’s return type and use // @ts-expect-error to confirm that invalid argument combinations, such as a GET with a body, are rejected. Runtime tests target the single implementation with each argument shape, because the overloads add nothing executable; a branch-coverage report confirms every Array.isArray or typeof dispatch path runs.
Troubleshoot. The most frequent error is “This overload signature is not compatible with its implementation signature”, which means the implementation’s parameter or return union does not cover an overload; widening the implementation fixes it. Callers hitting “No overload matches this call” get a long error listing every attempt; reading the last listed overload usually reveals the mismatch, and reordering overloads from specific to general prevents a broad signature from shadowing a precise one. Passing a union value to an overloaded function fails because overloads do not distribute; adding a union overload or narrowing first resolves it.
The important consideration is that overloads are a type-level contract only: the implementation must enforce the same rules at runtime for untyped callers.
A declaration file (.d.ts) contains only type information, with no implementation: the shapes of functions, classes, variables and modules that exist at runtime somewhere else. Ambient declarations, written with the declare keyword, tell the compiler that a value or module exists without producing any code for it. Both are how TypeScript understands JavaScript libraries, browser and Node APIs (lib.dom.d.ts, @types/node), and globals injected by a host.
// globals.d.ts: injected by the build or runtime, not imported
declare const __APP_VERSION__: string;
// vendor.d.ts: an untyped npm package
declare module "legacy-analytics" {
export function track(event: string, props?: Record<string, unknown>): void;
}
// express.d.ts: augment a third-party module
import "express";
declare module "express" {
interface Request { user?: { id: string } }
}How they are found:
types / exports entry in package.json, or the community publishes them in @types/* from DefinitelyTyped.tsc --declaration generates .d.ts files for a library’s own source so consumers get types without the source.include in tsconfig, /// <reference types="..." />, or the types option.This diagram shows the resolution path for a module’s types.
A .d.ts file with no top-level import or export is a global script and its declarations are visible everywhere; adding either makes it a module.
Apply. In a monorepo the shared @acme/core package builds with declaration: true and declarationMap: true so consuming apps get types and “go to definition” jumps to source. A src/types/ folder holds ambient declarations: env.d.ts typing process.env and import.meta.env, assets.d.ts declaring *.svg and *.css modules for the bundler, and augmentations of Express and Fastify request objects. Untyped vendor scripts get a minimal declare module stub with a TODO to replace it with @types when available. skipLibCheck: true is set so third-party .d.ts conflicts do not block the build, while the project’s own declarations are still checked.
Test. Published declarations are validated with @arethetypeswrong/cli and publint in CI, which catch wrong exports conditions and missing types for ESM and CJS consumers. A smoke test project in the repo imports the built package exactly as a consumer would and runs tsc --noEmit against it. Type tests confirm augmentations landed, for example expectTypeOf<Request["user"]>().
Troubleshoot. “Could not find a declaration file for module ‘x’” (TS7016) is fixed by installing @types/x or adding a stub. An augmentation that silently has no effect is almost always in a .d.ts that lacks any import or export, which makes it a global script that declares a new express module instead of merging; adding import "express" fixes it. Duplicate identifier errors between @types/node versions are solved with a single pinned version via overrides. Types resolving to any for an ESM consumer typically mean the exports map lacks a types condition, which arethetypeswrong reports directly.
The important consideration is that declaration files are trusted and unverified; a wrong .d.ts produces confident code that fails at runtime.
Both model a closed set of named values, but an enum is a TypeScript-specific construct that emits a runtime object, while a literal union is purely a type with no emitted code. In modern TypeScript the union, usually paired with an as const array or object, is generally preferred.
| Aspect | enum | Literal union / | as const |
|---|---|---|---|
| Runtime | Emits an object (numeric enums get reverse mapping) | Nothing emitted unless an array is written | as const |
| Values | Numeric by default; string enums possible | Strings, numbers, or template literals | |
| Nominality | Enum members are not assignable from plain literals | Plain "active" | is assignable |
| Iteration | Object.values(Enum) (numeric enums include names) | Iterate the as | const array |
| Tooling | const enum inlines but breaks isolatedModules and Babel/esbuild | Works with every transpiler |
enum Status { Active = "active", Suspended = "suspended" }
let s: Status = "active"; // error: string literal not assignable
const STATUSES = ["active", "suspended"] as const;
type StatusU = (typeof STATUSES)[number];
let u: StatusU = "active"; // ok, and STATUSES is iterable at runtimeNumeric enums have a soundness hole: before TypeScript 5.0, any number was assignable to a numeric enum type; 5.0 made all enums union enums and tightened this to known values. String enums give nominal-style safety, which some teams want for IDs and currency codes. const enum should be avoided in libraries because consumers using isolatedModules or non- tsc transpilers cannot inline it.
Apply. The house convention for new code is literal unions backed by as const arrays: ORDER_STATUSES is the array used for the database check constraint, the Zod z.enum(ORDER_STATUSES) schema, the OpenAPI enum list and the TypeScript type, so there is one source of truth. String enums remain in a few places where nominal safety is wanted, such as distinguishing CurrencyCode from arbitrary strings, and in generated gRPC/Protobuf clients that produce them. const enum is banned in shared packages by lint because the build uses esbuild with isolatedModules.
Test. A type test asserts the union equals the expected literal set and a runtime test asserts ORDER_STATUSES has no duplicates and matches the database enum via a migration snapshot. For the remaining enums, tests check Object.values(Enum) against the API contract, because adding a member to a string enum silently extends what the API accepts.
Troubleshoot. The most common incident is a numeric enum serialised to JSON as 0, 1, 2 and then reordered in source, which changes the meaning of stored data; the fix is explicit string values or a migration to a literal union. const enum members “not found” at runtime after switching to esbuild or Babel is the inlining problem; converting to a regular enum or union fixes it. Comparisons like status === Status.Active failing against data from the wire indicate the wire carries a plain string while the enum is numeric. Hover errors showing Status.Active not assignable to "active" mean two models are mixed; a single mapping function at the boundary resolves it.
The important consideration is that an enum is one of very few TypeScript features that changes emitted JavaScript, so it is the exception to “types are erased”.
TypeScript follows ECMAScript modules: any file with a top-level import or export is a module with its own scope; files without them are global scripts. Types and values travel through the same import / export syntax, but types are erased, so the compiler must decide which imports are type-only and remove them from the output. Import types are the explicit way to say that.
// Named type-only import: fully erased, never a runtime dependency
import type { Order, OrderStatus } from "./order";
// Inline type modifier (4.5+): mix in one statement
import { createOrder, type OrderInput } from "./order";
// Export a type without emitting anything
export type { Order } from "./order";
// Type-level import without an import statement
type Repo = import("./repository").OrderRepository;The diagram shows what survives emit: value imports stay, type-only imports vanish.

Why this matters:
isolatedModules and transpilers that process one file at a time (esbuild, swc, Babel), the tool cannot know whether Order is a type, so explicit import type prevents a runtime import of something that does not exist.verbatimModuleSyntax (5.0+) makes the rule mechanical: imports without type are kept exactly as written, so a type imported without the modifier is an error.module and moduleResolution (node16, nodenext, bundler) decide how specifiers resolve and whether .js extensions are required in ESM output.Decorators metadata and importsNotUsedAsValues interactions are the usual reason an import that looks unused survives into the output.
Apply. A Node 20 service compiled as ESM uses "module": "nodenext" with verbatimModuleSyntax: true, so every type import carries type, relative imports carry .js extensions, and the output runs on Node without a bundler. The front end uses "moduleResolution": "bundler" with Vite, where isolatedModules is on because esbuild strips types per file. Lint rule @typescript-eslint/consistent-type-imports auto-fixes missing type modifiers, and import type is the only permitted way for the domain layer to reference infrastructure types, which keeps the dependency graph acyclic at runtime.
Test. CI builds the package and runs a consumer smoke test from both an ESM and a CommonJS entry point, plus @arethetypeswrong/cli for the exports map. madge --circular runs over the compiled JavaScript so a type-only cycle is allowed but a runtime cycle fails the build. A test asserts the bundle does not contain modules that should have been erased, by grepping the output for a known type-only module name.
Troubleshoot. “SyntaxError: The requested module does not provide an export named ‘Order’” at Node startup means a type was imported as a value and esbuild left the import in place; verbatimModuleSyntax turns it into a compile error. ERR_MODULE_NOT_FOUND for ./order is the missing .js extension under nodenext. undefined at runtime from a circular import, often surfacing as “Class extends value undefined”, is diagnosed with madge and fixed by converting the cycle’s type edges to import type and moving shared runtime code to a third module. “Cannot use import statement outside a module” is a package.json type field mismatch with the emitted format.
The important consideration is that the compiler’s module settings and the actual runtime or bundler must agree; most module bugs are a disagreement between the two.
tsconfig.json tells the compiler which files form a project and how to check and emit them. The options fall into a few groups, and most incidents come from a handful of them.
| Group | Key options | Effect |
|---|---|---|
| Type checking | strict, noUncheckedIndexedAccess, exactOptionalPropertyTypes | How much unsoundness is rejected |
| Modules | module, moduleResolution, verbatimModuleSyntax, paths | How imports resolve and are emitted |
| Emit | target, outDir, declaration, sourceMap, noEmit | What JavaScript and .d.ts are produced |
| Interop | esModuleInterop, allowJs, resolveJsonModule, lib, types | Working with JS, JSON and host APIs |
| Project | include, exclude, references, composite, incremental | Which files, and multi-project builds |
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"strict": true,
"noUncheckedIndexedAccess": true,
"verbatimModuleSyntax": true,
"skipLibCheck": true,
"declaration": true,
"outDir": "dist"
},
"include": ["src"]
}Points that are frequently misunderstood:
strict is an umbrella that turns on strictNullChecks, noImplicitAny, strictFunctionTypes, useUnknownInCatchVariables and others; new flags can join it in future releases.target changes which syntax is down-levelled and, through the default lib, which built-in APIs are known; it does not polyfill anything.extends lets a repo share a base config (@tsconfig/node20, @tsconfig/strictest) and override per package.noEmit: true plus tsc in CI keeps type checking while leaving transpilation to the faster tool.The compiler reads options at the project root; files not matched by include are still pulled in if imported.
Apply. In a monorepo a root tsconfig.base.json extends @tsconfig/strictest and pins module, target, strict, noUncheckedIndexedAccess and verbatimModuleSyntax; each package has a tiny tsconfig.json that extends it and sets only outDir, rootDir and references. Type checking and emitting are separated: tsc -b --noEmit -style checks run in CI while esbuild or Vite produce the JavaScript, so developers get fast builds without losing checks. paths aliases are mirrored in the bundler config, and incremental with a committed-ignored .tsbuildinfo keeps local checks fast. The split is shown below.

Test. A CI job runs tsc --showConfig and diffs it against a committed snapshot so an accidental change to effective options is reviewed explicitly. Each package has a type-test file that fails if a strictness flag is removed, for example // @ts-expect-error on arr[0].toFixed() which only errors under noUncheckedIndexedAccess. Build output is tested by running the compiled entry point on the target Node version in CI.
Troubleshoot. “Cannot find module” in tests but not in the build is a paths alias not mirrored in Vitest or Jest configuration. A new lib API such as Array.prototype.at reported as missing means target or lib is older than the runtime. Slow tsc is profiled with --extendedDiagnostics and --generateTrace; common causes are a missing include that pulls in node_modules tests, or skipLibCheck off. Mysterious behaviour differences between editor and CLI come from the editor picking a different tsconfig, visible in the TS server log.
The important consideration is that the compiler options describe the runtime the code will run on, so target, lib and module must be set from the deployment environment rather than copied from a template.
TypeScript decides compatibility by shape, not by name: a value is assignable to a type if it has at least the required members with compatible types, regardless of which interface or class it was declared with. This is structural typing, in contrast to the nominal typing of Java or C# where only an explicit implements or inheritance relation counts.
interface Point { x: number; y: number }
class Vector { constructor(public x: number, public y: number) {} }
const p: Point = new Vector(1, 2); // ok: same shape, no 'implements' needed
const q: Point = { x: 1, y: 2, z: 3 }; // error: excess property (fresh literal)
const extra = { x: 1, y: 2, z: 3 };
const r: Point = extra; // ok: non-literal, extra props allowedConsequences worth stating:
UserId and OrderId both as string gives no protection against mixing them.q fails and r succeeds.private and protected members make a class nominal in practice: another class with the same private name is not compatible.type UserId = string & { readonly __brand: "UserId" } is assignable only from values deliberately cast or produced by a constructor function.Structural typing is what lets TypeScript describe existing JavaScript so well: an object literal, a class instance and a JSON.parse result can all satisfy the same interface.
Apply. In a payments service structural typing is used deliberately for dependency injection: handlers depend on interface PaymentGateway { charge(...): Promise<Receipt> } and tests pass a plain object literal with the same methods, no mocking framework or class hierarchy needed. Where structural equivalence is dangerous, identifiers are branded: AccountId, TransactionId and Cents are branded primitives created by small constructor functions, so a Cents cannot be passed where a Percentage is expected despite both being numbers. Adapters between an external SDK’s types and internal domain types rely on structure, so an SDK upgrade only breaks the adapter when a required field actually changes.
Test. Type tests assert both directions: a fake gateway literal is assignable to the interface, and AccountId is not assignable to TransactionId (// @ts-expect-error). Contract tests run the real adapter against recorded SDK responses to catch structural drift that the type definitions may not reflect.
Troubleshoot. The signature incident is swapped arguments of the same primitive type, such as transfer(toId, fromId), that compiles and moves money the wrong way; branding the IDs makes the next occurrence a compile error. Excess-property errors that appear when extracting an inline literal into a variable, or disappear when doing the reverse, confuse developers; satisfies on the variable restores the check. “Types have separate declarations of a private property” when two copies of a class library are installed is resolved by deduplicating the dependency, since private members made the class nominal.
The important consideration is that structural typing will happily accept any object with the right fields, so semantic distinctions between same-shaped types must be added explicitly with brands or wrapper objects.
An API boundary is any point where data enters the program from outside the compiler’s view: HTTP bodies and query strings, JSON.parse, environment variables, message queues, localStorage, database drivers returning loosely typed rows, and third-party webhooks. Because types are erased, an annotation such as const body = req.body as Order is a promise with no enforcement; the correct discipline is to type the raw input as unknown and convert it to a trusted type through runtime validation in one place.
import { z } from "zod";
const OrderInput = z.object({
customerId: z.string().uuid(),
items: z.array(z.object({ sku: z.string(), qty: z.number().int().positive() })),
});
type OrderInput = z.infer<typeof OrderInput>;
export function parseOrder(raw: unknown): OrderInput {
return OrderInput.parse(raw); // throws ZodError with field paths on failure
}The flow is: untrusted unknown at the edge, a parser or type guard that either produces a typed value or a structured error, and fully typed code inside. This picture shows the boundary.

Casting (as) and non-null assertions are the anti-pattern at boundaries because they produce confident downstream code that fails far from the cause. The same applies to outgoing data when the consumer has a stricter contract than the type system can express, such as string length limits.
Apply. In an order API every Fastify route declares a schema, and the handler receives the parsed, typed body rather than touching req.body directly; the parsing and HTTP 400 mapping live in one middleware. Environment configuration is parsed once at startup by an Env schema so a missing DATABASE_URL crashes the process immediately with a clear message instead of a vague failure under load. Queue consumers parse each message envelope and route unparseable ones to a dead-letter queue with the validation error attached. Database rows from the driver are typed via the query builder’s generated types, and anything coming from a JSONB column is still parsed, because the column’s content is not guaranteed.
Test. Boundary parsers are tested with a fixture set of valid payloads plus one invalid variant per rule (wrong type, missing field, out-of-range number, unexpected extra key) asserting the error path. Contract tests replay recorded upstream responses against the schema so a provider change surfaces in CI rather than production. A type test asserts the handler’s body type equals z.infer<typeof schema> so the two cannot diverge.
Troubleshoot. The symptom of a missing boundary check is a TypeError deep in business logic with a stack trace that does not include the request handler; the first step is to log the raw payload at the edge and find the path where it was cast. A spike in 400 responses after a deploy usually means a schema was tightened without coordinating with the client, visible in the structured error logs by field path. Validation that passes locally but fails in production often traces to environment-specific data such as numeric strings from query parameters, fixed with z.coerce.
The important consideration is to validate exactly once per boundary; duplicating checks in every layer adds latency and drift without adding safety.
Zod is a TypeScript-first schema library: a schema is defined once as a value, used at runtime to validate and parse data, and used at compile time via z.infer to derive the static type. This solves the erasure problem directly, since the runtime check and the type come from the same definition and cannot drift.
import { z } from "zod";
const Customer = z.object({
id: z.string().uuid(),
email: z.string().email(),
tier: z.enum(["free", "pro"]).default("free"),
tags: z.array(z.string()).max(10).optional(),
});
type Customer = z.infer<typeof Customer>;
// { id: string; email: string; tier: "free" | "pro"; tags?: string[] }
const result = Customer.safeParse(JSON.parse(raw));
if (!result.success) console.error(result.error.issues); // path, code, message
else saveCustomer(result.data); // typed CustomerCore behaviours:
parse throws a ZodError; safeParse returns a discriminated union { success: true; data } | { success: false; error }..strict() rejects them, .passthrough() keeps them), defaults are applied, and .transform can change shape, giving distinct z.input and z.output types..extend, .pick, .omit, .partial, z.union, z.discriminatedUnion, .refine for cross-field rules, and z.coerce for strings from query parameters.zod/mini build, and some API changes such as error-message customisation moving to a unified error parameter.Alternatives include Valibot, ArkType, io-ts and TypeBox; the pattern is identical even if the API differs.
Apply. In a subscription billing service the Zod schemas are the canonical contract: route handlers parse bodies with them, the Env schema validates configuration at startup, webhook payloads from the payment provider are parsed with z.discriminatedUnion("type", [...]), and OpenAPI documentation is generated from the same schemas via zod-to-openapi. Front-end forms reuse the schemas through react-hook-form ’s resolver so client and server rules match. Schemas live in a shared package and are versioned with the API. This pipeline shows where parsing sits.

Test. Each schema has a table of accepted and rejected fixtures, asserting the exact issues[].path and code for rejections so error responses stay stable for clients. Type tests check that z.infer<typeof Customer> equals the domain type the rest of the code uses. Benchmarks run with tinybench on the hottest schemas because validation cost on a high-throughput endpoint is real.
Troubleshoot. Unexpectedly missing fields after parsing are the default key-stripping behaviour, usually when a client sends fields the schema does not list; .passthrough() or adding the field fixes it. A type mismatch where the handler sees string | undefined for a field with .default() is the z.input versus z.output distinction; use z.output or z.infer. Confusing union errors are improved by switching z.union to z.discriminatedUnion, which also parses faster. Performance regressions in a hot path are addressed by parsing once at the edge, not again in every service layer, and by upgrading to Zod 4.
The important consideration is that Zod validates structure and simple invariants; business rules needing a database lookup belong in the service layer, not in .refine.
An async function always returns a Promise<T> where T is the type of the value it returns, and await unwraps Promise<T> to T. The compiler enforces this: declaring async function f(): number is an error, and await on a non-promise is allowed but flagged by lint as pointless. Promise<void> is the type of an async function that returns nothing.
async function fetchOrder(id: string): Promise<Order> {
const res = await fetch(`/orders/${id}`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return (await res.json()) as Order; // json() is Promise<any>; validate it
}
const [a, b] = await Promise.all([fetchOrder("1"), fetchUser("u")]);
// a: Order, b: User (tuple inference preserves per-element types)
const settled = await Promise.allSettled([fetchOrder("1")]);
// PromiseSettledResult<Order>[] -> narrow on .status === "fulfilled"Points that come up:
Awaited<T> (4.5+) recursively unwraps nested promises and thenables, and is used in the signatures of Promise.all, race, any, allSettled.Promise<T> says nothing about the error, and catch (e) gives unknown under strict. Typed failures need a result union or a library such as neverthrow.Promise<T> | T should be normalised with await or Promise.resolve.fetch().json() and JSON.parse return any, which is the main leak of unsafety in async code.await yields a Promise<Order> where an Order was expected; the type error catches it unless the value is only used in a boolean or void context, which is where @typescript-eslint/no-floating-promises and no-misused-promises step in.Apply. In a fulfilment service every I/O method on repositories and clients returns Promise<T> with an explicit annotation, so the interface is honest about asynchrony and consumers cannot forget it. Errors that callers are expected to handle are modelled as a Result<T, DomainError> union returned from the promise, leaving thrown rejections for genuinely unexpected failures. Fan-out uses Promise.all for tuples of heterogeneous calls and Promise.allSettled where partial success is acceptable, narrowing on status. AbortSignal parameters are passed through so timeouts and cancellation compose. The lint rules no-floating-promises, no-misused-promises and require-await are errors, not warnings.
Test. Unit tests use await expect(fn()).rejects.toThrow(...) and resolves matchers, and fake timers (vi.useFakeTimers) to drive retry and timeout logic deterministically. Type tests assert Awaited<ReturnType<typeof fetchOrder>> equals Order and that passing an async callback to array.forEach is a lint error. Integration tests run with --unhandled-rejections=strict so a missed rejection fails the suite.
Troubleshoot. The most frequent production bug is a missing await inside a try, so the catch never fires and the rejection becomes an unhandledRejection event; the Node process logs it and, in strict mode, exits. The lint rules above catch the pattern statically. Promise<Order> appearing in a template string as [object Promise] is the same omission. Deadlocks from await inside a for loop over hundreds of items show as latency; converting to batched Promise.all with a concurrency limiter such as p-limit resolves it. A handler returning Promise<void> where the framework expected a value is caught by no-misused-promises.
The important consideration is that the type system tracks the success type only; rejection types are invisible to it and must be designed explicitly.
Migrating a JavaScript codebase to TypeScript is incremental by design: the compiler accepts .js files alongside .ts, every JavaScript program is valid TypeScript once types are permissive enough, and strictness can be tightened file by file. The typical path is shown below.
Key mechanics:
allowJs includes JavaScript files in the program; checkJs type-checks them using inference and JSDoc annotations (/** @type {Order} */, @param, @returns, @typedef), which gives real checking before any file is renamed..ts with noImplicitAny off and strict off compiles almost immediately; any and // @ts-expect-error are used as temporary scaffolding and tracked.@types/* or local declare module stubs.noImplicitAny, then strictNullChecks, then the rest), often with a tool that enforces strict mode only on migrated files.tsc --noEmit for checking while the existing bundler or Babel handles emit, so the pipeline barely changes.Since TypeScript 5.5, --isolatedDeclarations and 5.x JSDoc improvements also make the checkJs stage more capable, and codemods such as ts-migrate automate the rename and insertion of placeholder annotations.
Apply. For a 200-file Express service, the migration starts with allowJs and checkJs in a new tsconfig, which surfaces hundreds of latent bugs through inference alone without touching a file. The leaf modules with the fewest dependents (utilities, constants, validators) are converted first so their types propagate upward; routes and controllers go last. A typescript-strict-plugin or a second tsconfig.strict.json with an explicit include list keeps converted files at full strictness while the rest remain loose. Every temporary any is written as // TODO(ts-migrate): any so it is countable, and the count is a tracked metric that must trend to zero before the strictness flag flips globally.
Test. The existing test suite is the safety net and runs unchanged throughout, since the emitted JavaScript is behaviourally identical. CI adds tsc --noEmit as a required check and a script that fails the build if the any count or the error count under the strict config increases, which prevents regression while allowing partial progress. Converted modules gain type tests for their exported contracts.
Troubleshoot. Thousands of errors on first checkJs run are triaged by tsc --noEmit | sort | uniq -c on error codes; TS7006 (implicit any parameter) and TS2339 (property does not exist) dominate and are often one wrong JSDoc @typedef cascading. Runtime behaviour differences after conversion are almost always a changed target downlevelling class fields or a esModuleInterop change altering default imports; aligning the config with the previous Babel settings fixes them. Slow checks on the mixed codebase are addressed with incremental and by excluding generated directories.
The important consideration is that the migration’s value comes from strictness, not from the file extension, so a codebase full of any after renaming has gained little.
Add your resume and the job description in CrackItX's Settings. When the interviewer asks a TypeScript question, Claude suggests an answer using your real projects and the role's requirements, in real time.
See pricing →