Skip to content
Tech Interview Prep
Technical interview guideNew

TypeScript for Frontend Engineers

TypeScript's type system as frontend code actually uses it: structural typing, generics, narrowing, utility types, and typing React props, hooks and events. Plus what the compiler catches at build time, what it erases, and where runtime validation is still required.

Read
18 min
Practice MCQs
25
Interview Q&A
25
Edition
v1
Editorial status
Reviewed
Relevant for
Frontend Engineer

Scope: TypeScript 5.x (checked against 5.8), React 18 and 19 with @types/react 18/19. `satisfies` requires TS 4.9+; inferred type predicates require 5.5+; `verbatimModuleSyntax` requires 5.0+. Defaults quoted are from the TS 5.8 `tsc --init` output..

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-3

Walk me through `any`, `unknown` and `never`: how each one is assignable, and where you'd actually reach for each in a React codebase.

Answer

The 90-second answer. These three are the top, the bottom, and the escape hatch in TypeScript's type lattice.

  • unknown is the top type. Every type is assignable to it; it is assignable to nothing except any and itself. You can store, pass and compare an unknown, but you cannot read a property, call it, or add it to a number until you narrow it.
  • never is the bottom type. It is assignable to everything; nothing is assignable to it except never itself. It describes a value that cannot exist.
  • any is assignable in both directions with every type: with one exception, never. Every operation on it type-checks. That is not a position in the lattice; it is the switch that turns the checker off for that value and everything derived from it.
from ↓ to →anyunknownneverstring
any✓✓✗✓
unknown✓✓✗✗
never✓✓✓✓
string✓✓✗✓

The any → never cell is the one asymmetry worth memorising: any is assignable to every type except never, so const x: never = someAny is an error. Union and intersection behaviour falls out of the same positions: unknown | string collapses to unknown, never | string to string, unknown & string to string, never & string to never.

Where each is correct. unknown at every boundary you don't control: JSON.parse, response.json(), postMessage, catch bindings, third-party callbacks. never for exhaustiveness and for filtering unions. any almost nowhere: a short-lived bridge during a JS→TS migration, and even there // @ts-expect-error with a reason beats it, because it starts failing once the underlying error is fixed.

The boundary is the argument that matters. lib.dom types Response.json() as Promise<any>, so the leak starts at the first await:

// any: compiles, ships, throws in production when the API renames a field
const data = await res.json();
return data.user.email;          // no error even when user is null

// unknown: the annotation is the whole fix
const data: unknown = await res.json();
return data.user.email;          // TS18046: 'data' is of type 'unknown'

Now the compiler forces a decision. Either a hand-written guard:

function isUser(v: unknown): v is User {
  if (typeof v !== 'object' || v === null) return false;
  const o = v as Record<string, unknown>;
  return typeof o.id === 'string' && typeof o.email === 'string';
}

or a schema validator at the edge (zod, valibot) whose parse returns a typed value or throws with a path like user.email: Expected string, received null. Either way the failure moves from a component render to the network boundary, where you can log it, render an error state, and keep the rest of the app typed.

never earns its place in the exhaustiveness check:

type Shape = { kind: 'circle'; r: number } | { kind: 'square'; s: number };

function area(s: Shape): number {
  switch (s.kind) {
    case 'circle': return Math.PI * s.r ** 2;
    case 'square': return s.s ** 2;
    default: {
      const exhaustive: never = s;   // a third variant breaks the build here
      return exhaustive;
    }
  }
}

Failure modes. any is contagious: one Promise<any> infects every call site downstream and a field rename ships green. Detect it with @typescript-eslint/no-unsafe-assignment, no-unsafe-member-access and no-unsafe-return in CI: they fire on any flowing into typed code, which no-explicit-any alone does not catch. catch (e: any) reintroduces the same bug for thrown non-Errors: throw 'boom' leaves e.message undefined. Since TS 4.4 useUnknownInCatchVariables (on under strict) types the binding unknown, and the fix is e instanceof Error ? e.message : String(e). A never return annotation is trusted rather than verified at the call site: callers use it for control-flow analysis, so a function annotated : never that can actually return makes the compiler treat everything after the call as unreachable and silently drop narrowing. The symptom is a missing error, not a type error. The guard is that every path in the body throws or loops, which is a review and test obligation.

Curated: · Written: · Reviewed:

Q&A-1

How do you decide between `type` and `interface` in a codebase you own, and what makes that default defensible?

Answer

Say this first. Pick by what the type has to do, then make the trivial case a lint rule so code review stops relitigating it.

interface when the shape is open: another file or a library may merge into it, a class implements it, or consumers extend it. type when the shape is closed or is not an object at all: unions, tuples, primitives, template literals, mapped and conditional types, anything derived with Pick/Omit/ReturnType. For { id: string } the two compile identically, so a repo-wide default is a convention; the defensible part is knowing exactly where it stops. Mine: interface for exported object shapes, type for everything else, enforced with @typescript-eslint/consistent-type-definitions.

interfacetype
Declaration mergingyes: same-name interfaces merge across filesno: second declaration is Duplicate identifier
Can nameobject types only (properties, call, construct, index signatures)anything
extends vs &interface C extends A, B checked at the declarationtype C = A & B unchecked; conflicts surface at each use
Implicit index signaturenoyes, on aliases of object literal types
Relation cachingrelations between named types are cachedanonymous intersection alias is re-evaluated
Third-party augmentationdeclare module / declare global mergesnot possible

Merging is the one that decides real code.

declare global {
  interface Window { __APP_CONFIG__: AppConfig }  // merges into lib.dom's Window
}
window.__APP_CONFIG__;  // typed

type Window = ... here is a duplicate identifier that loses the DOM members rather than adding to them. Same story for augmenting express-serve-static-core or any library that ships an interface.

extends errors at the declaration; & errors at the use site.

interface A { x: number }
interface B { x: string }

interface C extends A, B {}
// error TS2320 at C: Interface 'C' cannot simultaneously extend types 'A' and 'B'.
//                   Named property 'x' of types 'A' and 'B' are not identical.

type D = A & B;            // accepted — no error here
declare const d: D;
d.x;                       // hover: never
const bad: D = { x: 1 };   // error: Type 'number' is not assignable to type 'never'.

The intersection version is worse under review: the message names never, not A or B, and it fires wherever the value is used, three files from the mistake.

The gotcha that looks like a compiler bug. Interfaces are open, so TypeScript can never prove one has only string-valued properties; object literal aliases are closed, so it can.

interface Foo { a: string }
type Bar = { a: string };
declare function headers(h: Record<string, string>): void;
declare const f: Foo, b: Bar;
headers(b); // ok
headers(f); // error: Index signature for type 'string' is missing in type 'Foo'.

Detection for both traps is the same: any never on hover means an intersection conflict, and go-to-definition landing in two files means a merge you did not plan.

In React, interface ButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement> { variant?: 'primary' | 'ghost' } is the readable shape, but a polymorphic as prop needs React.ComponentPropsWithoutRef<E> with generics, which only a type alias can express, so a strict interface-only policy costs you there.

Performance is a tie-breaker, not a migration. TypeScript's performance guidance prefers interfaces over intersections because named relations are cached; that guidance predates most of today's checker and the gap is small, visible mainly on large shapes used in many assignability checks. Measure before claiming it: tsc --extendedDiagnostics prints check time and instantiation count, and tsc --generateTrace trace writes a trace you can open in Perfetto or chrome://tracing. Real wins usually come from skipLibCheck, narrower project references and splitting giant unions.

Curated: · Written: · Reviewed:

Q&A-2

Assigning `const opts = { label: 'Go', handler }; render(opts)` compiles, but inlining the same object into `render({ label: 'Go', handler })` fails. Why the difference, and how would you fix the inline version without a cast?

Answer

The 90-second answer. Assignability in TypeScript is structural: a type is compatible with another if it has at least the required members, with compatible types. An object with extra fields therefore satisfies a narrower target: that is the rule that lets { label, handler } be passed anywhere a { label } is expected. Excess property checking is a second rule layered on top, not a soundness fix: it fires only when the source expression is a fresh object literal, i.e. a literal written at the use site. The moment the value is named through a variable, the check stops. Its purpose is to catch typo'd keys: { colur: 'red' } is dead config that a structural check would accept forever, so the compiler refuses fresh literals whose keys don't appear on the target type.

// TypeScript 5.5, strict mode
type ButtonProps = { label: string; onClick: () => void };
declare function Button(props: ButtonProps): void;

const opts = { label: 'Go', handler: () => {} }; // { label: string; handler: () => void }
Button(opts);                                   // OK — extra fields are fine

Button({ label: 'Go', handler: () => {} });
// error TS2353: Object literal may only specify known properties,
//   and 'handler' does not exist in type 'ButtonProps'.

Same value, same target type, two verdicts. The only difference is freshness.

Fixing it without a cast.

  1. Hoist the literal. const opts = {...}; Button(opts);: no longer fresh, the check is skipped. Cheapest and honest. The cost is total: that object is now unchecked against ButtonProps for a misspelled required key too, so you traded a narrow check for none.
  2. Widen the target type. If handler is genuinely part of the contract, declare it on ButtonProps. If it belongs to a bigger config object that several components each consume a slice of, declare that object once and give each component the field it actually needs.
  3. Make the parameter generic. function Button<T extends ButtonProps>(props: T): T accepts any object with at least label, preserves the concrete type at the call site, and never applies the fresh-literal check because the target is a type parameter. This is the one to reach for on builders or wrappers that hand the object back.
  4. Don't reach for [key: string]: unknown. An index signature does silence the error, but it accepts every spelling mistake at every call site and turns every property access into a lookup that may be unknown. That is worse than the cast you were avoiding.

Where else it fires, and where it doesn't. The check follows freshness, not assignment, so:

ExpressionTargetChecked?
literal passed inlineconcrete object typeyes (TS2353)
literal returned from a function with an annotated return typeconcrete object typeyes
nested literal inside a fresh literalnested concrete typeyes, recursively
variable holding the same objectconcrete object typeno
identical literal, generic parameter T extends TargetTno
literal, union-of-objects targeteach memberonly if the key is on no member

That table is why the error can vanish during a refactor: changing Button({...}) into const p = {...}; Button(p) silently drops the check for the whole object, and changing it back brings it in. A type test file is how you notice: put // @ts-expect-error above an assertion that assigns an unknown key to the type. If the annotation ever becomes unnecessary, TypeScript will flag the unused @ts-expect-error, and you know the check was lost.

I would say in an interview that the check is a linting heuristic wearing a type error's clothes, and that the review question is not "how do I silence TS2353" but "is handler a typo or a real field?" Hoisting is the right answer for the first; widening the type is the right answer for the second.

Curated: · Written: · Reviewed:

Q&A-4

Walk me through how TypeScript narrows a union (`typeof`, `instanceof`, `in`, discriminant properties, type predicates) and what `as` does instead of narrowing?

Answer

Narrowing is control-flow analysis. The compiler gives each reference a declared type, and after a check it recognises, the type is reduced on each branch to what that check proves. The compiler verifies the check's logic, so the result is only as strong as the check. as skips this step entirely.

The five checks, under strict in TypeScript 5.4:

CheckNarrows whenBlind spot
typeof x === 'string'x is a union that includes primitivestypeof null === 'object'; does nothing between two object types
x instanceof Datex is a class instance from the same realmobjects from an iframe or vm context fail the check
'radius' in xsome members declare radiusproves presence only, not that x.radius has the type you expect
x.kind === 'circle'kind is a literal type on each membera string-typed kind narrows nothing
isCircle(x)always, because the compiler trusts the signaturethe body can disagree with the signature

A discriminated union is the case to lead with, because the compiler checks every branch:

type Shape =
  | { kind: 'circle'; radius: number }
  | { kind: 'square'; side: number }
  | { kind: 'rect'; w: number; h: number };

function area(s: Shape): number {
  switch (s.kind) {
    case 'circle': return Math.PI * s.radius ** 2;
    case 'square': return s.side ** 2;
    case 'rect':   return s.w * s.h;
    default: {
      const unhandled: never = s;   // s is never here
      throw new Error(`unhandled ${JSON.stringify(unhandled)}`);
    }
  }
}

Each case removes the other members, so s.radius checks. If you add { kind: 'tri'; base: number; height: number } to the union and do not add a case, const unhandled: never = s stops compiling, because s is now the triangle member. This is the exhaustiveness check.

A type predicate moves the proof into a function you wrote:

const isSquare = (s: Shape): s is Extract<Shape, { kind: 'square' }> =>
  typeof s === 'object';   // compiles; wrong for every Shape

The compiler does not check the body against the signature. Called on a circle, s.side is undefined at runtime while the type says number. Prefer discriminants where the data has one, and keep predicates next to the code that validates the data.

as is a claim with no runtime effect:

const s = JSON.parse(input) as Shape;       // no validation
const c = s as Extract<Shape, { kind: 'circle' }>;
c.radius;   // compiles; throws at runtime if input was a square

The compiler only requires the two types to be comparable. s as Date is rejected because Shape and Date do not overlap. s as unknown as Date is accepted, and its presence in a diff is a sign that the assertion is hiding a mismatch. as const is a different feature: it makes literals readonly and narrow, and has nothing to do with narrowing unions.

Failure modes and how to detect them

  1. typeof x === 'object' is true for null, so if (typeof x === 'object') x.foo throws when x is null. Detect with x !== null && typeof x === 'object', and check null in unit tests for every object branch.
  2. instanceof is realm-bound. An array from another realm fails arr instanceof Array. Use Array.isArray, which works across realms.
  3. Narrowing and closures. Since TypeScript 5.4, a narrowed let keeps its narrowing inside a closure only when the closure is created after the variable's last assignment. Otherwise the closure sees the declared type. Copy the value to a const before creating the closure, which works on any version.
  4. any disables narrowing. JSON.parse returns any, so checks on its result narrow nothing and errors surface far from the cause. Assign the result to unknown, then narrow with predicates or a schema validator.

Answer order for an interview: state that narrowing is flow analysis, name the five checks and their blind spots, show the exhaustive switch, say why predicates are trusted rather than verified, and close with as as an unchecked claim. Mention the closure rule and any if time allows.

Curated: · Written: · Reviewed:

Q&A-5

How would you model a component's loading/success/error state as a discriminated union, and what happens at compile time when someone adds a new variant?

Answer

The 90-second answer. Give the state one literal discriminant and put the payload only on the variant that has it:

// TypeScript 5.4, strict: true
type Async<T> =
  | { status: 'idle' }
  | { status: 'loading' }
  | { status: 'success'; data: T }
  | { status: 'error'; error: Error };

Then switch on status and close with a never check:

function assertNever(x: never): never {
  throw new Error(`Unhandled variant: ${JSON.stringify(x)}`);
}

function UserList({ state }: { state: Async<User[]> }) {
  switch (state.status) {
    case 'idle':
    case 'loading':
      return <Spinner />;
    case 'success':
      return <List users={state.data} />;   // data: User[], no guard needed
    case 'error':
      return <ErrorBox error={state.error} />;
    default:
      return assertNever(state);
  }
}

Two things fall out. Inside case 'success', state.data is User[], not User[] | undefined, because the discriminant narrowed the union. And the default branch is only reachable if state is never, so the compiler proves the switch covers every variant.

What happens when someone adds a variant. Add | { status: 'empty' } to Async and the build breaks at every consumer, not at the type:

error TS2345: Argument of type '{ status: "empty"; }' is not assignable to parameter of type 'never'.

The assignment form gives the same thing with a different code:

default: {
  const _exhaustive: never = state;   // TS2322: Type '{ status: "empty"; }' is not assignable to type 'never'.
  return _exhaustive;
}

That error is the whole point: the union is a checklist, and adding a row fails every place that hasn't ticked it.

Why not booleans. { isLoading: boolean; data?: T; error?: Error } has 2³ = 8 representable combinations and 4 meaningful ones. { isLoading: true, error: someError } compiles, and state.data! is the non-null assertion that follows. The union makes the other four unrepresentable.

three booleansdiscriminated union
representable states84
{ loading: true, error: e }compilesnot a type
add a variantnew flag, no errors anywhereevery switch errors

All of this assumes strict: true. With strictNullChecks off, data?: T collapses to T, so the boolean version compiles with no error at all.

Failure modes.

  1. Discriminant widened to string. { status: string; data?: T } doesn't narrow: state.data is T | undefined in every branch and the never default never fires, because string is never exhausted. Detect by hovering state.status, if it isn't a union of literals, the pattern is dead. Fix with an explicit literal union or as const where the object is built.
  2. A default: that renders a fallback. Compiles, and the new variant silently shows a spinner forever. The only acceptable body is assertNever. Grep for default: in switches over state.
  3. A cast at the fetch boundary. (await res.json()) as Async<User[]> makes the compiler believe the shape. A 500 body of {"status":"error"} with no error narrows to the error case and state.error.message throws. Validate at the boundary (zod, valibot); the union is a compile-time claim, not a runtime guarantee.
  4. Transitions aren't checked. The union says which states exist, not which moves are legal: loading → loading type-checks. If that matters, put the union in a useReducer with a discriminated action union and test the transition table.

Alternatives. A mapped type over Async<T>['status'] with satisfies gives the same exhaustiveness for a render map instead of a switch, and Extract<Async<T>, { status: 'success' }> pulls out one variant when a helper needs it. Both are the same idea: one literal key, checked by the compiler.

Curated: · Written: · Reviewed:

Q&A-13

Walk me through the utility types you actually reach for (`Partial`, `Required`, `Pick`, `Omit`, `Record`, `Readonly`, `ReturnType`, `Parameters`, `Awaited`) what each produces, and when deriving a type from an existing one beats redeclaring it?

Answer

The 90-second answer. Utility types are type-level functions. Most are mapped types over an object type's keys; ReturnType, Parameters and Awaited are conditional types that use infer over a function or a thenable. The decision rule: derive when a source of truth already exists in the codebase (a function, a component's props, an API response) because a derived type breaks at compile time when the source changes, while a redeclared one drifts silently until runtime. Redeclare when the two types are genuinely independent contracts, or when you want a narrower public surface than the internal type.

UtilityProduces
Partial<T>same keys, all optional; shallow
Required<T>same keys, ? modifier removed; shallow
Pick<T, K>only keys in K, requiredness preserved
Omit<T, K>keys of T not in K; not a strict inverse of Pick
Record<K, V>object with exactly keys K mapped to V
Readonly<T>same keys, readonly added; shallow
ReturnType<F>F's return type
Parameters<F>tuple of F's parameter types
Awaited<T>recursively unwraps promises and thenables

ts // TypeScript 5.4, strict async function fetchUser(id: string, opts?: { signal?: AbortSignal }) { return { id, name: 'Ada', createdAt: new Date() }; }

type User = Awaited<ReturnType<typeof fetchUser>>; // { id: string; name: string; createdAt: Date } type FetchArgs = Parameters<typeof fetchUser>; // [id: string, opts?: { signal?: AbortSignal } | undefined] type UserId = Parameters<typeof fetchUser>[0]; // string

type UserPatch = Partial<Pick<User, 'name'>>; // { name?: string } type UserDraft = Omit<User, 'createdAt'>; // { id: string; name: string }

The drift trace. Change fetchUser to return { id, displayName }. User follows, and every consumer that read .name fails to compile. A hand-written interface User { name: string } keeps compiling and returns undefined at runtime. That is the whole argument for deriving: the compiler is the only thing that notices a rename.

Failure modes, and how you catch each.

  1. Omit over a union is not distributive. keyof (A | B) is the intersection of the keys, so Omit<Cat | Dog, 'x'> collapses to the shared keys and silently drops the rest. Detect: hover the alias, or assign a full Cat to it and read the excess-property error. Fix: type DistributiveOmit<T, K extends keyof any> = T extends any ? Omit<T, K> : never;
  2. Partial and Readonly are shallow. Partial<Config> still requires every nested field; Readonly<State> does not stop state.items.push(x). Detect: a test that assigns {} to a nested object, or a mutation that compiles when you expected it not to. Fix: a recursive DeepPartial/DeepReadonly, or ReadonlyArray<T> on the array field.
  3. ReturnType on an overloaded function takes the last overload signature. Detect: hover. Fix: annotate the return type explicitly, or derive from a single-signature alias.
  4. Record<string, V> is an index signature: it requires no keys and permits any. Record<'a' | 'b', V> requires exactly those two. Pick deliberately; the first is a map, the second is a closed set.

When redeclaring wins. A domain model and a component's props are different contracts. Deriving props from the model means a backend field rename forces a UI change and couples the two release cycles. Derive the internal shape, then Pick the narrow public surface you actually promise.

Curated: · Written: · Reviewed:

Q&A-17

Walk me through `satisfies`, `as const` and a plain type annotation on an object literal: which one keeps the literal keys, which one keeps the literal values, and why does annotating against a `Record` widen them?

Answer

The 90-second answer. These are three different operations, not three spellings of one thing. A type annotation replaces the expression's type: const a: Record<string, Handler> = { copy, paste } makes the binding exactly Record<string, Handler>, so the literal's key names are gone the moment the variable exists. as const is a const assertion: it stops widening and marks the object readonly, and validates nothing against a target shape. satisfies T (TypeScript 4.9+) checks the expression against T, excess property checks and union-key completeness included, then discards T and leaves the inferred type in place.

So the decision is: do you need the key names as a union. keyof typeof x, autocomplete, x.cop failing to compile? An annotation is the wrong tool. Do you need literal values as well (a readonly tuple, a 'copy' string you later match on)? Then you also need as const. Do you want a build error when a teammate adds a variant and forgets an entry? That is satisfies, with or without the as const.

// TypeScript 5.5, strict: true
type Handler = (id: string) => void;
declare const copy: Handler, paste: Handler;

const a: Record<string, Handler> = { copy, paste };
type K1 = keyof typeof a;   // string | number — the index signature, not 'copy' | 'paste'
a.cop;                      // compiles: dot access is allowed through a string index signature

const b = { copy, paste } as const;
type K2 = keyof typeof b;   // 'copy' | 'paste'
b.cop;                      // error: Property 'cop' does not exist

const c = { copy, paste } satisfies Record<string, Handler>;
type K3 = keyof typeof c;   // 'copy' | 'paste'
c.cop;                      // error — and the whole literal was checked against Record
formchecked against targetkeyof typeof xvalue types
const x: T = {...}yestarget's keys (index signature for Record<string, V>)target's
const x = {...} as constnoliteral keysliteral, readonly
const x = {...} satisfies Tyesliteral keyswidened, as a plain const
{...} as const satisfies Tyesliteral keysliteral, readonly

Two things surprise people.

Why the annotation widens the values. The annotation is a contextual type for the literal, and contextual typing widens a string literal in a mutable position to string; from then on the declared type wins for hover, keyof, indexed access and error messages. You also lose typo detection on read: noPropertyAccessFromIndexSignature is off by default and is not part of strict, so a.cop is legal and evaluates to undefined at runtime, far from the object literal that caused it.

satisfies does not de-widen anything. It validates the same inferred type a bare const would have produced, so const x = { label: 'Go' } satisfies Record<string, { label: string }> still gives x.label.label: string, not 'Go'. Literal values require as const.

The idiom that gets both is {...} as const satisfies T, and it has one real cost: as const makes arrays readonly, so { routes: ['/'] } as const is readonly ['/'], which is not assignable to string[]. A target of Record<string, string[]> stops compiling. Widen the target to readonly string[] or drop the as const.

Where this pays off in a React tree: const handlers = { copy, paste } satisfies Record<Action, Handler> errors when someone adds an Action variant and forgets the handler, an annotation to Record<Action, Handler> catches that too, but only satisfies keeps keyof typeof handlers as 'copy' | 'paste', so you can derive type Action = keyof typeof handlers instead of maintaining the union by hand and watching the two drift apart.

Curated: · Written: · Reviewed:

Q&A-24

Walk me through `enum`, `const enum`, a `const` object with `keyof typeof`, and a union of string literals: what each compiles to, how they tree-shake, and which you'd make a design-system `size` prop?

Answer

The 90-second answer. For a prop on a design system the type is a union of string literals. It has no runtime representation, so there is nothing to tree-shake and no value that can drift; consumers write size="md" with no import at all; and it is structural, so 'sm' | 'md' declared in two packages is the same type. When I need the values at runtime (a Storybook scale, a <select>, validation of a theme coming from JSON) I keep a const object and derive the type from it with keyof typeof. I use a plain enum only in code that already has them and never crosses a package boundary, and I never ship a const enum from a library.

What each one emits. This is the part that decides it. Input, compiled with tsc 5.x at target: ES2019:

type Size = 'sm' | 'md' | 'lg';                          // 1

const Size = { sm: 'sm', md: 'md', lg: 'lg' } as const;  // 2
type Size = (typeof Size)[keyof typeof Size];

enum Size { sm = 'sm', md = 'md', lg = 'lg' }            // 3

const enum Size { sm = 'sm', md = 'md', lg = 'lg' }      // 4
// 1: nothing at all
// 2: var Size = { sm: "sm", md: "md", lg: "lg" };
// 3:
var Size;
(function (Size) {
  Size["sm"] = "sm"; Size["md"] = "md"; Size["lg"] = "lg";
})(Size || (Size = {}));
// 4: nothing; every read is inlined at the use site
const a = "sm" /* Size.sm */;

A numeric enum also gets a reverse map, which is where iteration bugs come from:

Level[Level["Low"] = 0] = "Low";
// Object.values(Level) is ['Low', 'High', 0, 1]
runtime outputvalue list at runtimesafe in a published package
string unionnonenoyes
const object + keyof typeofone plain objectyesyes
enumIIFE-built object, reverse map if numericyesyes, but the bytes ship
const enuminlined literalsnono: cross-file inlining and version skew

const enum is the one that actually breaks. Inlining only works if the compiler sees the declaration and the use together. Babel and esbuild compile file by file and cannot see across modules, so a const enum declared in another file is emitted as a real object or rejected; isolatedModules: true makes tsc itself error with TS2748 ("Cannot access ambient const enums when 'isolatedModules' is enabled"), and preserveConstEnums turns it back into an ordinary object. The nastier failure is version skew: if a published library inlined 'sm', that literal is frozen inside every consumer's bundle, so correcting the value needs a rebuild of each consumer rather than a patch release. TypeScript 5.8's erasableSyntaxOnly rejects enum and const enum outright, the same reason Node's type stripping refuses them, which is the direction toolchains are moving.

Failure modes.

  1. Nominal friction. enum Tone { Danger = 'danger' } rejects tone="danger" from a caller who did not import Tone, because a string enum member is not assignable from a string literal. The workaround people reach for is as Tone, which is how casts get into a design system. Detect: grep for as Size.
  2. Reverse-map iteration. A variant scale rendered with Object.values(Level) on a numeric enum renders ['Low','High',0,1]: four entries for two variants. Detect: an assertion on the rendered count, or just never use numeric enums.
  3. Type-only import still shipping the object. import { Size } used only in a type position keeps the enum alive unless it is import type or the package sets sideEffects: false. Detect: the bundle analyzer shows the enum's chunk on a page that never reads a value.

A union has no runtime array, so it cannot validate the 'medium' a CMS sends: that is exactly the case for the const-object-plus-keyof typeof form, where one declaration gives you both.

Curated: · Written: · Reviewed:

Q&A-6

Walk me through typing a `get(key, fallback)` lookup over a typed config map: the constraint, the default type parameter, how inference resolves at the call site, and when you'd drop the generic for a union parameter.

Answer

The 90-second answer. A type parameter is a function over types: it lets the caller's types flow through the signature instead of being erased at the boundary. Three rules cover most of it. A constraint (K extends keyof ConfigMap) narrows what callers may pass and, more usefully, lets the body index into the parameter's type. A default (<T = unknown>) applies only when inference produces no candidate: it is not a fallback for a bad argument. Inference reads argument positions; a type parameter that appears in no parameter position can never be inferred, so it must be passed explicitly or defaulted.

The judgement call: use a generic when the relationship between argument and return types has to survive. Key to value, element to element, input to same-typed output. Use a union when every case is handled identically and the return type doesn't depend on which one you passed. A generic whose type parameter appears exactly once in the signature is a union (or unknown) in costume.

The signature, and what each piece buys.

// TypeScript 5.4, strict: true
interface ConfigMap { port: number; host: string; debug: boolean }
const store: Partial<ConfigMap> = {};

function get<K extends keyof ConfigMap>(key: K, fallback: ConfigMap[K]): ConfigMap[K] {
  return store[key] ?? fallback;
}

The constraint does two jobs: it rejects get('nope', 1) at the call site, and it makes ConfigMap[K] a legal indexed access in the body. That indexed access is the point: fallback is number when key is 'port' and string when it's 'host', with no overloads and no cast.

Inference trace.

CallK inferredfallback checked againstOutcome
get('port', 8080)'port'numberreturns number
get('host', 'localhost')'host'stringreturns string
get('port', '8080')'port'numbererror: string not assignable to number
get('nope', 1)——error: 'nope' not assignable to 'port' | 'host' | 'debug'

K infers to the literal 'port', not string, because the constraint is a union of literals. That is what keeps the indexed access precise.

Defaults. A default fires only when inference yields no candidate:

type ApiResponse<T = unknown> = { data: T; error?: string };
type Empty = ApiResponse;              // data: unknown

function createStore<S extends object = Record<string, never>>(initial?: S): S { /* ... */ }

With no default and no candidate, an unconstrained T resolves to unknown and a constrained one to its constraint. Defaulting to any discards the checking the generic existed for.

Generic or union. function format(v: string | number): string is right when the body branches once and returns the same type either way. function first<T>(xs: T[]): T | undefined is right because the element type must survive. The test: does the return type depend on which member of the union you passed? If yes, generic. If no, union: it gives simpler errors and no inference surprises.

Failure modes.

  1. Phantom type parameter. function log<T>(x: T): void: T appears once, so it is unknown with ceremony. Detect: a type parameter used in exactly one position.
  2. Constraint that doesn't connect. function get<T extends Record<string, unknown>>(obj: T, key: string): unknown: key is not keyof T, so the return is unknown and every caller casts. Detect: a generic function whose return type is unknown or any.
  3. Default masking inference failure. function parse<T = any>(s: string): T returns any at every unannotated call site, and noImplicitAny won't flag it. Detect: grep for = any in type parameter lists.
  4. Generic component in .tsx. <T>(props: Props<T>) parses as JSX; write <T,> or <T extends unknown>. Detect: "JSX element 'T' has no corresponding closing tag".

When you want the default to win rather than inference, NoInfer<T> (TypeScript 5.4) blocks inference from that position.

Curated: · Written: · Reviewed:

Q&A-14

Walk me through building a type that turns `{ name: string; age: number }` into `{ onNameChange: (v: string) => void; onAgeChange: (v: number) => void }`, and explain what `-?` and `-readonly` do in a mapped type.

Answer

The 60-second answer. A mapped type is a loop over keyof T; an as clause in the key position renames each key at the type level. Add a template literal and the Capitalize intrinsic and the handler names fall out mechanically:

// TypeScript 5.4, strict
 type ChangeHandlers<T> = {
  [K in keyof T as `on${Capitalize<K & string>}Change`]: (value: T[K]) => void;
};

type Form = { name: string; age: number };
type FormHandlers = ChangeHandlers<Form>;
// { onNameChange: (value: string) => void; onAgeChange: (value: number) => void }

K & string is not decoration. Capitalize is declared as type Capitalize<S extends string>, and K in a mapped type is string | number | symbol, so Capitalize<K> is a compile error: the intersection narrows it to the string keys, and the template literal handles the rest.

The - prefixes live in the modifier positions. { [K in keyof T]: T[K] } is a homomorphic mapped type: it copies the source's readonly and ? modifiers onto the result. Writing readonly or ? alone is shorthand for +readonly / +?, so those add. A leading - removes, which is exactly how the standard library defines Required<T>:

// lib.es5.d.ts
type Required<T> = { [P in keyof T]-?: T[P] };

type Flags = { readonly a: string; b: number };
type Cleared = { -readonly [K in keyof Flags]: Flags[K] };
// { a: string; b: number }

The as clause also filters: remap a key to never and the property disappears, which is how you keep only the string-valued props.

type StringHandlers<T> = {
  [K in keyof T as T[K] extends string ? `on${Capitalize<K & string>}Change` : never]: (v: T[K]) => void;
};

Pin it with a type test, not a hover. A wrong mapping is still a valid type, so nothing goes red until a call site breaks.

type Equal<A, B> = (<T>() => T extends A ? 1 : 2) extends (<T>() => T extends B ? 1 : 2) ? true : false;
const check: Equal<ChangeHandlers<{ name: string }>, { onNameChange: (v: string) => void }> = true;
// compile error if the mapping drifts

Failure modes.

  1. Type-correct, runtime-wrong. onAgeChange: (value: number) => void says nothing about Number.parseInt(e.target.value) yielding NaN, which is a perfectly good number. The type checks the shape; parse and validate at the boundary.
  2. Modifiers you didn't notice. A source readonly or ? propagates into the generated handlers. When the mapped type emits a props interface, an optional source prop makes the handler optional where you needed it required: add the - prefix deliberately rather than discovering it.
  3. Unreadable errors through a generic. A failure inside ChangeHandlers<Form> is reported against the whole alias, not the offending key. Keep the alias small and test it once at its definition instead of debugging through it at each call site.

Ship it or hand-write it? Eleven props and the mapped type wins: adding email to Form adds onEmailChange everywhere with no edits. Two or three props and hand-writing is cheaper than the type gymnastics. Either way the implementation needs one as or Proxy internally, so the benefit is a checked call-site surface, not a checked implementation.

Curated: · Written: · Reviewed:

Q&A-15

Walk me through conditional types and `infer`: how you'd extract a promise's resolved type and a function's return type, and why conditional types distribute over naked type parameters?

Answer

The 90-second answer. A conditional type is an if at the type level: T extends U ? X : Y. infer declares a type variable inside the pattern being matched, so T extends Promise<infer U> ? U : T reads "if T is a Promise, bind its argument to U and return it". The rule that bites is distribution: when the checked type is a naked type parameter (T, not [T] or T & {}) the conditional splits a union into its members, evaluates each, and unions the results. That is exactly what makes Exclude work, and exactly what makes a naive IsString<T> return boolean for 'a' | 1.

// TypeScript 5.4, strict: true
type Unwrap<T> = T extends Promise<infer U> ? U : T;

type A = Unwrap<Promise<number>>;           // number
type B = Unwrap<Promise<Promise<string>>>;  // Promise<string> — one level only
type C = Unwrap<string>;                    // string

type D = Awaited<Promise<Promise<string>>>; // string — the library version recurses

type MyReturnType<T extends (...args: any) => any> =
  T extends (...args: any) => infer R ? R : any;

type E = MyReturnType<() => Promise<number>>;   // Promise<number>
type F = Awaited<ReturnType<typeof loadUser>>;  // what loadUser resolves to

Unwrap is one level deep and stops at a thenable. Awaited (TS 4.5) recurses and unwraps thenables, so in a React loader you write Awaited<ReturnType<typeof loadUser>> rather than hand-rolling the one-level version.

Distribution, traced.

type Boxed<T> = T extends unknown ? T[] : never;
type R1 = Boxed<string | number>;   // string[] | number[]
type R2 = Boxed<never>;             // never
StepExpressionResult
1Boxed<string | number>T is naked → split the union
2string extends unknown ? string[] : neverstring[]
3number extends unknown ? number[] : nevernumber[]
4union the branchesstring[] | number[]

never is the empty union, so there is nothing to distribute over: Boxed<never> is never, not never[]. To opt out, wrap both sides in a one-tuple:

type BoxedWhole<T> = [T] extends [unknown] ? T[] : never;
type R3 = BoxedWhole<string | number>;  // (string | number)[]

Failure modes, and how you catch each.

  1. Distribution where you wanted the whole union. type IsString<T> = T extends string ? true : false; IsString<'a' | 1> is boolean. Detect: a helper that returns true | false instead of one literal. Fix: [T] extends [string].
  2. any in the checked position. any extends string ? 1 : 2 is 1 | 2: any matches both branches. A generic helper instantiated with any, which is what you get from an untyped JSON.parse, silently widens. Detect: hover the instantiation and read the union.
  3. Contravariant infer intersects. type Arg<T> = [T] extends [(a: infer A) => any] ? A : never; Arg<((a: string) => void) | ((a: number) => void)> is string & number, i.e. never. Covariant positions union their candidates; contravariant ones intersect. The tuple wrapper is what forces the intersection here: without it, distribution would have split the union first.
  4. Deferred resolution. Inside function f<T>(x: T), Unwrap<T> stays unevaluated until T is known. It is a type-level computation only; it cannot narrow a runtime value.

Where it pays off in a React codebase: React.ComponentProps<typeof Button> for wrapper components, Awaited<ReturnType<typeof loader>> for route data, and Exclude/Extract over an action union to derive the reducer's handled cases.

Curated: · Written: · Reviewed:

Q&A-16

Walk me through deriving a union of event names and route params from a const object with `keyof typeof` and template literal types, and what breaks when the derivation is wrong?

Answer

The 90-second answer. Three pieces compose. as const freezes an object literal so its property values keep their literal types instead of widening to string. typeof in type position reads the type of a value, and keyof turns that type's keys into a union. Template literal types then rewrite string literal unions into other string shapes. Put together, one const object is the source of truth for event names, route strings and the handler names derived from them.

const routes = {
  home: '/',
  user: '/users/:userId',
  post: '/users/:userId/posts/:postId',
} as const;

type Route = (typeof routes)[keyof typeof routes];
// '/' | '/users/:userId' | '/users/:userId/posts/:postId'

const handlers = {
  signup: (e: SignupEvent) => {},
  checkout: (e: CheckoutEvent) => {},
} as const;

type EventName = keyof typeof handlers;        // 'signup' | 'checkout'
type OnName = `on${Capitalize<EventName>}`;    // 'onSignup' | 'onCheckout'

Why as const is load-bearing. Without it, routes is { home: string; user: string; post: string }, so Route is string and navigate('/userz/:id') compiles. The keys survive without as const, object literal keys are already literal, but any derivation that reads a value collapses. The same collapse happens if you annotate the object: const handlers: Record<string, Handler> = {...} makes EventName string, and emit('signp') is accepted.

Extracting params. A recursive conditional type over the template literal pulls the :name segments out:

type Params<T extends string> =
  T extends `${string}:${infer P}/${infer R}` ? P | Params<`/${R}`>
  : T extends `${string}:${infer P}` ? P
  : never;

type UserParams = Params<typeof routes.user>; // 'userId'
type PostParams = Params<typeof routes.post>; // 'userId' | 'postId'

This is compile-time only. It does not validate a URL at runtime; if routes arrive from a CMS, the type is an assertion, not a check, and you need a runtime parser at the boundary.

The cost of getting it wrong. A widened union is silent: the typo compiles, ships, and the handler lookup returns undefined at 2 a.m. A hand-written type EventName = 'signup' | 'checkout' | 'logout' drifts the moment someone adds a key to the object: the object has a handler the union doesn't know about, or the union names an event with no handler. When the union is the source of truth (an API contract, say), tie the object to it with satisfies:

type EventName = 'signup' | 'checkout';

const handlers = {
  signup: (e: SignupEvent) => {},
  checkout: (e: CheckoutEvent) => {},
} satisfies Record<EventName, Handler>;

satisfies checks the object against the union without widening it, so a missing key is an error and an extra key is an excess-property error.

Failure modes and detection.

  1. Widened literal. Hover EventName; if it says string, the as const or the annotation is wrong. A type-level assertion (type _ = Expect<Equal<EventName, 'signup' | 'checkout'>>) fails the build instead of the review.
  2. Drift. Add a key to the object and run tsc; without satisfies, nothing fails. With it, the missing handler is a compile error.
  3. Recursion depth. Deeply nested template literal types hit "Type instantiation is excessively deep" around 50 levels for non-tail-recursive forms. Keep route patterns shallow and precompute the union rather than deriving per call site.
  4. Checker cost. A union of 200 routes × 3 params is fine; 5,000 is a slow tsc for everyone. Measure with --diagnostics before adopting the pattern at scale.

When not to. If the strings are runtime data, template literal types buy nothing: validate with a schema. If the union is small and stable, a hand-written union plus satisfies is simpler and reads better in errors.

Curated: · Written: · Reviewed:

Q&A-7

Why does `const Select = <T>(props: SelectProps<T>) => ...` fail to compile in a `.tsx` file, what's the fix, and how does `T` get inferred when the component is used as JSX?

Answer

The 90-second answer. In a .tsx file the parser is in JSX mode, so a leading <T> on an arrow function is read as the opening tag of a JSX element named T, not as a type-parameter list. The compiler fails with a JSX error, "JSX element 'T' has no corresponding closing tag", before it ever type-checks the body. The fix is to give the parser something that cannot be a tag name: a trailing comma, <T,>, or a constraint, <T extends unknown>. Function declarations (function Select<T>(...)) are unambiguous and need neither.

Once it parses, the generic is a property of the call signature, so each JSX usage instantiates T independently from the attribute expressions. The element's type is the component's return type: by default JSX.Element, i.e. React.ReactElement<any, any>, so T does not survive into the element unless you annotate the return type yourself.

// TypeScript 5.4, React 18, strict
type SelectProps<T> = {
  options: readonly T[];
  value: T;
  onChange: (next: T) => void;
  renderOption: (option: T) => React.ReactNode;
};

// const Select = <T>(props: SelectProps<T>) => ...   // JSX element 'T' has no corresponding closing tag
const Select = <T,>({ options, value, onChange, renderOption }: SelectProps<T>) => (
  <ul>
    {options.map((o) => (
      <li key={String(o)} aria-selected={o === value} onClick={() => onChange(o)}>
        {renderOption(o)}
      </li>
    ))}
  </ul>
);

const fruits = ['apple', 'pear'] as const;

<Select
  options={fruits}                    // T = "apple" | "pear"
  value="apple"
  onChange={(f) => f.toUpperCase()}   // f: "apple" | "pear"
  renderOption={(f) => f}
/>;

options: readonly T[] against readonly ["apple", "pear"] infers the literal union, not string, because the array is as const. Drop the as const and T widens to string: inference takes the type of the expression you passed; it does not narrow it for you.

Where inference breaks.

  1. No inference site. If T appears only in a callback position, type Props<T> = { onSubmit: (values: T) => void }, there is nothing to infer from, and T falls back to unknown. The caller's (values) => values.email then errors on unknown. Fix: pass the type argument explicitly in JSX, supported since TypeScript 2.9: <Form<SignupValues> onSubmit={...} />. A runtime schema value cannot drive inference; only a type can.
  2. React.memo erases it. memo's signature is memo<P extends object>(c: FunctionComponent<P>): NamedExoticComponent<P>. Handing it a generic function instantiates P once, so const MemoSelect = React.memo(Select) is NamedExoticComponent<SelectProps<unknown>> and callbacks come back as unknown. Detect it by hovering the memoised component in the editor; the fix is a cast to the generic function type, or skipping memo on the generic component and memoising the row instead.
  3. React.FC cannot be generic. const Select: React.FC<SelectProps<T>> has no T in scope: React.FC fixes the props type at the annotation. Use a plain generic arrow function or a generic function declaration.

What the element type actually is. <Select options={fruits} ... /> has the type of Select's return type. With the implicit return above that is JSX.Element = ReactElement<any, any>, so a variable holding the element tells you nothing about T. Annotating ): React.ReactElement<SelectProps<T>> => makes the instantiated props type visible on the element, which is occasionally useful for wrapper components that clone children, but React's own JSX checking never reads it, so it buys documentation, not safety.

What not to do. <T,> is not a hack; it is the documented disambiguation. Reaching for as any on the props, or dropping to any for T, throws away exactly the inference the generic was there to provide: the caller's onChange parameter goes back to any and typos in renderOption stop being caught.

Curated: · Written: · Reviewed:

Q&A-8

How do you type React component props: `children` as `ReactNode` versus `ReactElement`, optional props with defaults, and where `React.FC` helps or hurts?

Answer

Short answer. Decide what the component does with children. If it lays them out (a card, modal or layout shell), type the prop ReactNode, which accepts strings, numbers, arrays, fragments, null and undefined. If it must inspect, clone or attach a ref to exactly one element, type it ReactElement and enforce cardinality at runtime. Optional props get destructuring defaults, not defaultProps. React.FC is a poor default: its one real convenience, implicit children, was removed from @types/react 18, and it cannot express generic components.

// React 18.3, @types/react 18.3, TypeScript 5.x
import type { ReactElement, ReactNode } from 'react';

type CardProps = {
  children: ReactNode;      // 'Save', <b/>, [<a/>, <b/>], null all compile
  header: ReactElement;     // must be an element such as <Header />, not the Header function
  tone?: 'neutral' | 'danger';
};

function Card({ children, header, tone = 'neutral' }: CardProps) {
  return <section data-tone={tone}>{header}{children}</section>;
}

ReactNode versus ReactElement. ReactNode is a union: ReactElement | string | number | Iterable<ReactNode> | ReactPortal | boolean | null | undefined. ReactElement is only the { type, props, key } object. Consequences:

  • children: ReactElement accepts <Card><b>x</b></Card> and rejects <Card>Save</Card>, because the string is not an element.
  • It also rejects <Card>{items.map(...)}</Card>, since an array is not a single element.
  • It does not enforce cardinality. ReactElement accepts children={[<a/>, <b/>]}, which is an array passed where one element was expected.

If the component truly needs one element, the type cannot guarantee it. Add a runtime check:

const only = React.Children.only(children); // throws unless exactly one valid element

In development, a violation throws React.Children.only expected to receive a single React element child. The failure is loud, which is the point. Silently rendering an array into a slot that expected one element is the bug you are avoiding.

The reverse trap: a prop typed ReactElement rejects a component reference. icon={Warning} is a function, not an element, so it fails to compile. That is the correct outcome, because a function reaching the tree throws Functions are not valid as a React child. If the API really takes a component, type it ComponentType<WarningProps> and usually supply a default.

Optional props. children?: ReactNode and children: ReactNode differ in whether the key must be present. ReactNode already includes undefined, so the ? is what lets callers omit the prop. Without it, <Card /> fails with a missing-property error, which is correct when the component requires children.

function Badge({ count = 0 }: { count?: number }) {
  return <span>{count.toFixed(0)}</span>;
}

The default in the destructuring supplies the value and narrows the type inside the body. Callers can omit count, and the implementation sees number, never number | undefined.

Badge.defaultProps = { count: 0 } achieved the same thing under older types through LibraryManagedAttributes. React 18.3 warns about defaultProps on function components, and React 19 removed support for them. Classes still accept it. Do not start new function components with it.

Where React.FC hurts.

React.FC<P>annotated plain function
implicit childrenremoved in @types/react 18not present; declare it yourself
generic componentcannot bind T in FC<P<T>>works
displayNametyped as string | undefinedneeds a cast if assigned to a function
type ListProps<T> = { items: T[]; render: (item: T) => ReactNode };
function List<T>({ items, render }: ListProps<T>) { /* ... */ }
// const List: React.FC<ListProps<T>> = ...  // error: T is not in scope

Failure to watch for: a team moves to @types/react 18 and components that relied on implicit children stop type-checking. The error shows up as a missing children property at call sites, not at the component. Detect it by running tsc --noEmit after the upgrade, and fix it by adding children to the props type explicitly or by using PropsWithChildren<P>, which is P & { children?: ReactNode }.

Verdict. Annotate a plain function's props and skip the wrapper. FC adds little beyond a typed displayName. For components that take children alongside their own props, write PropsWithChildren<P> or declare children directly, and pick ReactNode unless the code has to inspect a single element.

Curated: · Written: · Reviewed:

Q&A-9

Walk me through how you type `useState`, `useRef` and `useEffect`, where inference gets it wrong and what you annotate instead.

Answer

The 90-second answer. Three separate rules, and interviewers usually want all three.

useState infers its type parameter from the initial value, and a string literal in that position widens to string. So useState('idle') gives [string, Dispatch<SetStateAction<string>>]: setStatus('idel') compiles, and a switch over the value has no exhaustiveness check. Annotate the parameter: useState<Status>('idle') gives Status and a setter accepting Status | ((prev: Status) => Status).

useRef picks its overload from the argument, and that decides nullability. useRef<HTMLDivElement>(null) matches the T | null overload, so current is HTMLDivElement | null and every read needs a guard. useRef<number>(0) matches the plain T overload and current is number, never null. The no-argument form useRef<number>() gives number | undefined.

Effect dependencies are typed readonly unknown[]. The compiler checks the array's shape, not its contents: it will not tell you a dependency is missing. That is eslint-plugin-react-hooks's exhaustive-deps rule, not tsc.

// TypeScript 5.4, @types/react 18.3
type Status = 'idle' | 'loading' | 'done' | 'error';

const [a, setA] = useState('idle');           // string
const [b, setB] = useState<Status>('idle');   // Status
const [c, setC] = useState('idle' as const);  // 'idle' — setC accepts only 'idle'

setA('idel');  // compiles. This is the bug the annotation prevents.
setB('idel');  // error 2345: '"idel"' is not assignable to type 'Status'

as const is the wrong fix here: it pins the state to the literal 'idle' and the setter rejects every other status. Annotate the parameter, not the value.

Lazy initialisers. The function form is called once on mount; the direct call runs on every render.

const [cfg, setCfg]   = useState(parseConfig());        // parseConfig() every render
const [cfg2, setCfg2] = useState(() => parseConfig());  // once, on mount

It is also an ambiguity, not just an optimisation. useState(handler) where handler is a function calls it as an initialiser and stores the return value. To store the function itself: useState<() => void>(() => handler).

Refs.

DeclarationcurrentNotes
useRef<HTMLDivElement>(null)HTMLDivElement | nullReact 18 types: readonly. React 19 types: mutable, and RefObject<T> is now { current: T }
useRef<number>(0)numbermutable ref, no null branch
useRef<number>()number | undefinedno-argument overload

useRef<HTMLDivElement>(null!) is the common shortcut and it is a lie for the first render. It survives in an effect because effects run after commit, when React has attached the node, but the same expression read during render is null at runtime while the type says otherwise.

Effects. EffectCallback is () => void | Destructor, which catches two real mistakes:

useEffect(() => {
  const id = setInterval(tick, 1000);
  return () => clearInterval(id);   // Destructor — fine
}, [tick]);

useEffect(() => items.push(x), []);            // error: number not assignable to void | Destructor
useEffect(async () => { await load(); }, []);  // error: Promise<void> not assignable

Failure modes and how you catch each.

  1. Widened state. A typo'd status compiles and the UI silently renders nothing for it. Detect: the switch has no never default branch, so nothing errors when a variant is added. Fix: annotate, then default: { const _x: never = status; }.
  2. Missing dependency. tsc is silent; the effect closes over a stale value. Detect: exhaustive-deps in CI, or a stale-value bug that only reproduces after the second render.
  3. Recreated dependency. An inline object or function in the dep array re-runs the effect every render. Detect: a console.count in the effect body, or React DevTools showing the effect firing on every commit. Fix: useCallback/useMemo, or move the value inside the effect.
  4. Non-null asserted ref. ref.current.focus() in the render body throws Cannot read properties of null on first paint. Detect: it fails only on the initial render, which is why it survives review.

One thing worth stating: React guarantees the useState setter identity is stable across renders, so omitting it from a dependency array is correct, and exhaustive-deps knows that. A useRef object is likewise stable, but ref.current is not, which is why reading it in a dep array is almost always a bug.

Curated: · Written: · Reviewed:

Q&A-10

Walk me through using `useReducer` with a discriminated action union: why it beats several `useState` calls for related state, and how the action union makes the reducer exhaustive.

Answer

The 90-second answer. Ask what moves together. If two or more fields must change in lockstep (a step size, a count and a history) separate useState calls let you represent states that should never exist: count bumped, history not. useReducer collapses that into one named transition applied to one object, so the only way to change state is to dispatch an action, and the reducer is a pure function you can test without a renderer.

The action union is what makes it type-safe. Each action carries a literal type, so switch (action.type) narrows action to exactly one member and its payload is typed inside that case. Add a variant and the never default stops compiling.

// TypeScript 5.4, React 18
type State = { count: number; step: number; history: number[] };

type Action =
  | { type: 'increment' }
  | { type: 'decrement' }
  | { type: 'setStep'; step: number }
  | { type: 'reset'; step?: number };

function reducer(state: State, action: Action): State {
  switch (action.type) {
    case 'increment':
      return { ...state, count: state.count + state.step, history: [...state.history, state.count] };
    case 'decrement':
      return { ...state, count: state.count - state.step, history: [...state.history, state.count] };
    case 'setStep':
      return { ...state, step: action.step };   // action.step is number here
    case 'reset':
      return { count: 0, step: action.step ?? 1, history: [] };
    default: {
      const exhaustive: never = action;         // error the moment a variant is unhandled
      return state;
    }
  }
}

const [state, dispatch] = useReducer(reducer, { count: 0, step: 1, history: [] });

dispatch is typed Dispatch<Action>, a union of call signatures: dispatch({ type: 'setStep' }) without step is a compile error, and dispatch({ type: 'increment', by: 2 }) fails the excess-property check.

What the exhaustiveness check buys you. In the default branch, control-flow analysis has narrowed action to never because every variant was handled. Add | { type: 'undo' } to Action and that line becomes Type '{ type: "undo"; }' is not assignable to type 'never': an error at the reducer, not a silent no-op at runtime. Drop the default and TypeScript still catches it, but as "not all code paths return a value" on the function signature, which points at the wrong line. The never assignment names the missing case.

Why not three useState calls.

three useStateone useReducer
Atomicitythree setters, three intents; a throw between them leaves half-applied stateone dispatch, one transition
Illegal statescount and history can disagreeonly reachable states are constructible
Testingneeds a renderer or a hook-testing libraryreducer(s, { type: 'increment' }), plain function
Stale readsa handler closing over count writes the old valuethe reducer always receives React's current state
Identitysetters are stabledispatch is stable too, safe in useEffect deps

React 18 batches the three setters into one render, so render count is not the argument: the argument is that nothing in the type system stops the three from disagreeing.

Failure modes.

  1. Impure reducer. Mutating state or calling Date.now() inside it. React 18 StrictMode double-invokes reducers in development, so a mutation surfaces as a double increment that only happens in dev. Detect: call the reducer twice on the same input and compare.
  2. Widened action type. A helper returning { type: string } instead of a literal kills narrowing and the never check passes vacuously. Detect: hover action in the default branch. It should read never.
  3. Derived state kept in parallel. Storing total in a second useState alongside items reintroduces the desync the reducer removed. Compute it in the reducer or at render.

When not to. One independent boolean, or a form whose fields never interact: useState is less ceremony and exhaustiveness buys nothing. Reach for useReducer when transitions have names and fields move together.

Curated: · Written: · Reviewed:

Q&A-11

Walk me through event handler typing in React: when does an inline handler infer for free, what are the types for `ChangeEvent<HTMLInputElement>`, `FormEvent<HTMLFormElement>` and `MouseEvent`, and why does extracting the handler force you to annotate it?

Answer

The 90-second answer. Inline handlers are typed by contextual typing. The JSX attribute has a declared type (onChange on <input> is ChangeEventHandler<HTMLInputElement>, which is (event: ChangeEvent<HTMLInputElement>) => void) and TypeScript uses that expected type to infer the arrow function's parameter. You write nothing. Extract the same arrow into a function declaration and the expected type is gone: a declaration has no context to infer from, so e falls back to implicit any and strict reports TS7006. The fix is to put the type back, and the better place is the function, not the parameter.

// TypeScript 5.6, @types/react 18.3, strict: true
import { useState } from 'react';

export function Signup() {
  const [email, setEmail] = useState('');
  return (
    <form onSubmit={(e) => { e.preventDefault(); }}>          {/* FormEvent<HTMLFormElement> */}
      <input value={email} onChange={(e) => setEmail(e.target.value)} />  {/* ChangeEvent<HTMLInputElement> */}
      <button onClick={(e) => console.log(e.clientX)}>Save</button>       {/* MouseEvent<HTMLButtonElement> */}
    </form>
  );
}

// TS7006: Parameter 'e' implicitly has an 'any' type.
function handleChange(e) { setEmail(e.target.value); }

// Fix A — annotate the parameter
function handleChangeA(e: React.ChangeEvent<HTMLInputElement>) { setEmail(e.target.value); }

// Fix B — annotate the function with the prop's own handler type (preferred)
const handleChange: React.ChangeEventHandler<HTMLInputElement> = (e) => setEmail(e.target.value);

Fix B keeps the parameter inferred and moves the check to the declaration: if the element type changes, the assignment fails there rather than at every JSX site.

JSXProp typeEvent typee.targete.currentTarget
<input onChange>ChangeEventHandler<HTMLInputElement>ChangeEvent<HTMLInputElement>EventTarget & HTMLInputElementEventTarget & HTMLInputElement
<form onSubmit>FormEventHandler<HTMLFormElement>FormEvent<HTMLFormElement>EventTargetEventTarget & HTMLFormElement
<button onClick>MouseEventHandler<HTMLButtonElement>MouseEvent<HTMLButtonElement>EventTargetEventTarget & HTMLButtonElement

That target column is the trap. ChangeEvent<T> redeclares target: EventTarget & T, so e.target.value typechecks. FormEvent<T> does not: target is the bare EventTarget and e.target.value is TS2339. Use e.currentTarget (always EventTarget & T) or new FormData(e.currentTarget).

Failure modes.

  1. One handler across <input> and <select>. ChangeEventHandler<HTMLInputElement> rejects the select. Either split them or widen to React.ChangeEvent<HTMLInputElement | HTMLSelectElement> and narrow on e.currentTarget.tagName.
  2. useCallback((e) => …, []). No contextual type reaches the callback, so e is implicit any. Annotate the parameter inside the callback; the useCallback generic follows from it.
  3. Name collision. import { MouseEvent } from 'react' shadows the DOM MouseEvent for the whole file. React's is generic with a default of Element; if you need the native one, alias the import.
  4. Casting to silence it. (e as any).target.value compiles and breaks at runtime on the submit path. The annotation is one line; the cast is a debt.

Deeper detail. React declares handler props with a bivariance hack (EventHandler<E> = { bivarianceHack(event: E): void }["bivarianceHack"]), so a handler typed for a wider event still assigns to a narrower prop. That is why a ChangeEvent<HTMLElement> handler is accepted on an <input>: convenient, and the reason a wrong-but-wider annotation does not error at the JSX site.

When not to annotate. If the handler is used once, inline it and let inference do the work. Annotate only when the handler is named, reused, or exported.

Curated: · Written: · Reviewed:

Q&A-12

Walk me through typing a React context: why `createContext(null)` plus a custom hook beats `createContext({} as T)`, and how you'd type a context whose value is a discriminated union?

Answer

The 90-second answer. createContext takes a default value, and that default is what a consumer reads when no provider sits above it in the tree. It is a runtime fallback, not a type annotation. The honest fallback for "no provider" is null: type the context T | null, keep it module-private, and export a hook that throws on null. Consumers then receive T with no null check at each call site, and the single place that can fail fails loudly with a message you wrote.

// React 19, @types/react 19, strict
import { createContext, useContext, useState, type ReactNode } from 'react';

type AuthState =
  | { status: 'loading' }
  | { status: 'anonymous' }
  | { status: 'authenticated'; user: User; token: string };

const AuthContext = createContext<AuthState | null>(null); // not exported

export function AuthProvider({ children }: { children: ReactNode }) {
  const [state] = useState<AuthState>({ status: 'loading' });
  return <AuthContext value={state}>{children}</AuthContext>; // React 18: <AuthContext.Provider>
}

export function useAuth(): AuthState {
  const value = useContext(AuthContext);
  if (value === null) throw new Error('useAuth must be used inside <AuthProvider>');
  return value; // narrowed to AuthState
}

Why {} as T is worse, mechanically. That assertion compiles because an assertion is legal when either type is assignable to the other, and every object type is assignable to {}. So {} as AuthState type-checks no matter what AuthState requires: the cast tells you nothing. It lies twice: the type claims status exists, and the runtime default is {}. A component rendered outside the provider reads auth.status === undefined, falls through every branch, and throws on auth.user.avatarUrl inside a branch the compiler called safe. The error surfaces in the consumer, one stack frame away from the missing provider.

The union value. Because the hook returns AuthState, the consumer narrows on the discriminant and the compiler correlates the payload:

function Avatar() {
  const auth = useAuth();
  if (auth.status !== 'authenticated') return null;
  return <img src={auth.user.avatarUrl} alt={auth.user.name} />; // user exists only here
}

Destructuring first destroys that: const { status, user } = useAuth() breaks the correlation and user errors as not existing on all members. Keep the object and narrow on auth.status.

PatternRuntime defaultuseContext typeMissing provider shows up
createContext<T | null>(null) + hooknullT | nullat the hook call, your message
createContext({} as T){}T (a lie)at a property access elsewhere
createContext(realDefault)a real valueTnever: silently uses the default

Row three is legitimate when a default is meaningful (theme 'light', feature flags {}); then the hook needs no check. It is wrong when the value is per-request data.

Failure modes. A test that renders a consumer without the provider passes with {} as T and fails later on an assertion; with the null pattern it fails at the hook with a name. A provider passing a fresh object literal each render re-renders every consumer: memoise the value or split state and actions into two contexts so a dispatch-only button does not subscribe to state. And a no-op-function default for an actions context hides a missing provider exactly as {} does; prefer null there too.

When not to use the hook. If the value is genuinely constant for the process (build config, a logger), a real default plus a plain useContext is simpler and the throw buys nothing.

Curated: · Written: · Reviewed:

Q&A-18

Walk me through what `strict`, `strictNullChecks`, `noImplicitAny`, `noUncheckedIndexedAccess` and `exactOptionalPropertyTypes` each catch, and what it costs to turn them on in a codebase that shipped without them?

Answer

The 90-second answer. strict is a bundle, not a check. It flips eight flags at once: strictNullChecks, noImplicitAny, noImplicitThis, strictFunctionTypes, strictBindCallApply, strictPropertyInitialization, alwaysStrict, useUnknownInCatchVariables. Two of the flags you named are not in it: noUncheckedIndexedAccess and exactOptionalPropertyTypes are separate opt-ins. So "our tsconfig has strict: true" tells you nothing about whether arr[0] can be undefined or whether { label: undefined } satisfies { label?: string }. That split is the whole migration story, because the bundle flags are mostly annotation work and the two opt-ins rewrite call sites.

FlagWhat it catchesCost late
strictNullChecksnull/undefined assignable to every type; also gates strictPropertyInitializationHighest: every unguarded deref errors
noImplicitAnyParameters and expressions that would silently be anyLowest: mostly adding annotations
noUncheckedIndexedAccessarr[i] / record[key] typed T instead of T | undefinedHigh and permanent: every index read needs a guard
exactOptionalPropertyTypes{ a?: string } accepting { a: undefined }Medium: breaks prop spreading and third-party types
// TypeScript 5.4, tsconfig: strict + noUncheckedIndexedAccess + exactOptionalPropertyTypes

function len(s: string) { return s.length; }
len(null);                       // strictNullChecks: 'null' not assignable to 'string'

function id(x) { return x; }     // noImplicitAny: 'x' implicitly has an 'any' type

const counts: Record<string, number> = {};
counts['a'].toFixed();           // noUncheckedIndexedAccess: possibly 'undefined'
const xs = [1, 2, 3];
xs[0].toFixed();                 // same — number[] index is number | undefined
const t: [number, number] = [1, 2];
t[0].toFixed();                  // fine — tuple index is known

interface Props { label?: string }
const a: Props = { label: undefined };  // exactOptionalPropertyTypes: error
const b: Props = {};                    // fine — absent is what '?' means

Note what noUncheckedIndexedAccess does not touch: known tuple indices, for...of, and tuple destructuring. It only widens index signatures and array element access.

Migration. Order matters. noImplicitAny first: it's mechanical, and it's the flag that makes the rest tractable, because untyped parameters are where any leaks in. Then strictNullChecks, which is the one you cannot apply per-file: it's a whole-program flag, so the boundary has to be a project boundary. Use project references or a per-directory tsconfig.json to freeze legacy directories at the old settings while new code compiles strict. Then exactOptionalPropertyTypes, then noUncheckedIndexedAccess last, because it's the only one that adds work to code that was already correct.

Ratchet the error count in CI. // @ts-expect-error is the right suppression rather than @ts-ignore: it errors when the line stops failing, so the suppression removes itself. Track the count as a number that can only go down.

Failure modes. The classic one is enabling noUncheckedIndexedAccess and silencing it with ! on every index: you paid the migration and kept the bug. Detect it by counting non-null assertions added in a diff; a PR that adds forty of them is a revert. The second is exactOptionalPropertyTypes against React props: <Comp label={maybeUndefined} /> stops compiling against label?: string. The fix is either to widen the prop to label?: string | undefined or to spread conditionally, {...(maybeUndefined !== undefined && { label: maybeUndefined })}, not to cast. Third: skipLibCheck: true is effectively mandatory once you turn these on, because node_modules .d.ts files you don't own will fail and you can't fix them.

Curated: · Written: · Reviewed:

Q&A-19

A teammate writes `if (data instanceof User)` where `User` is an interface, and it won't compile. Explain why, and walk me through what actually survives to runtime and how you'd validate data at the network boundary instead.

Answer

The 90-second answer. TypeScript's types are erased. The compiler checks them, then emits JavaScript with every annotation, interface, type alias and generic parameter stripped out. An interface User therefore produces no runtime value at all, and data instanceof User is a compile error (TS2693, 'User' only refers to a type, but is being used as a value here) not a check that returns false. instanceof walks the prototype chain of its right-hand operand, so it needs a value that has one; an interface never does.

The consequence: anything crossing into your program from outside (res.json(), localStorage, postMessage, a query string, an env var) has whatever shape the wire gave it, and as User is an assertion the compiler accepts without checking a single field. The type is a claim. The only place a claim becomes a guarantee is a runtime validator at the trust boundary, with the static type derived from the validator so the two cannot drift.

// user.ts — nothing in this file exists after compilation
export interface User { id: string; role: 'admin' | 'member'; lastSeen: Date }

// broken.ts
const data = await res.json();
if (data instanceof User) { /* TS2693 — never compiles */ }
const user = data as User;   // compiles; checks nothing
user.role.toUpperCase();     // throws at runtime if role is missing
// boundary.ts — zod 3
import { z } from 'zod';

const UserSchema = z.object({
  id: z.string(),
  role: z.enum(['admin', 'member']),
  lastSeen: z.coerce.date(),
});

export type User = z.infer<typeof UserSchema>;   // one source of truth

const parsed = UserSchema.safeParse(await res.json());
if (!parsed.success) {
  // parsed.error.issues -> [{ path: ['role'], message: 'Invalid enum value...' }]
  throw new ApiError(parsed.error.issues);
}
const user: User = parsed.data;   // now the type is earned

What actually survives erasure:

ConstructRuntime artifact
interface, type alias, generic <T>none
annotation, as, satisfies, !none
classconstructor function + prototype
enumobject (with reverse mapping for numeric members)
const enuminlined and erased: breaks under isolatedModules
namespace with runtime membersIIFE
constructor(private x: T)assignment in the constructor
import typeremoved

Failure modes.

  1. The unchecked assertion. as User on a payload that lost a field compiles, and the error surfaces three components later as Cannot read properties of undefined. Detect: validate at the boundary and log parsed.error.issues. The path names the field the backend dropped.
  2. The lying type predicate. function isUser(x: unknown): x is User is trusted by the compiler; if the body only checks typeof x === 'object', the narrowing is wrong. Detect: unit-test the predicate against malformed payloads, not just valid ones.
  3. instanceof across realms. A class instance sent through postMessage or structuredClone arrives as a plain object, the structured clone algorithm does not preserve prototypes, so instanceof is false for a shape-correct value. Detect: brand the object with a literal field and check that instead.
  4. Type-only imports the bundler keeps. Without verbatimModuleSyntax, a value import of a type-only export survives to runtime and throws does not provide an export named. Detect: it fails in the browser, not in tsc.

Where not to validate. Not at every internal function boundary: that is the compiler's job and it costs CPU. Validate at trust boundaries only: network responses, storage reads, postMessage, URL params, third-party callbacks. Zod's full bundle is roughly 13 kB gzipped; valibot tree-shakes to a fraction of that for one schema, which matters if the boundary sits on a critical path. Parsing a 50-field payload costs tens of microseconds: irrelevant next to a network round trip, but not free in a loop over 10,000 rows, so validate once on entry and trust the type downstream.

Curated: · Written: · Reviewed:

Q&A-20

You call `fetch('/api/user')`, `await res.json()`, and cast the result to an interface you wrote by hand. Walk me through what the compiler actually checked, and how you'd type that response instead?

Answer

The 90-second answer. Nothing was checked. fetch returns a Response, and Response.json() is declared json(): Promise<any> in lib.dom.d.ts. any is assignable to everything and everything is assignable to any, so as User is an assertion the compiler accepts without comparing either side. The interface is a hand-written claim about a server you don't control, and it keeps compiling after the server changes. Treat the wire as unknown, parse it once at the edge, and let the rest of the app consume a type a runtime check actually produced.

// TypeScript 5.4, lib.dom
const res = await fetch('/api/user');
const user = (await res.json()) as User; // zero checking happened here

Parse once, at the edge. The boundary is the API client module, not the component. One parse per response; everything downstream trusts the type.

type User = { id: string; name: string; email: string | null };

class ParseError extends Error {}

function parseUser(input: unknown): User {
  if (typeof input !== 'object' || input === null) throw new ParseError('user: not an object');
  const o = input as Record<string, unknown>; // justified: typeof proved it's an object
  if (typeof o.id !== 'string') throw new ParseError(`user.id: expected string, got ${typeof o.id}`);
  if (typeof o.name !== 'string') throw new ParseError(`user.name: expected string, got ${typeof o.name}`);
  if (o.email !== null && typeof o.email !== 'string') throw new ParseError('user.email: expected string|null');
  return { id: o.id, name: o.name, email: o.email };
}

What the two versions do when the server changes. Say the backend now sends { id: 42, name: "Ada" }:

  • Cast version: user.id.toUpperCase() compiles, then throws TypeError: user.id.toUpperCase is not a function inside a render, with a stack that points at the component, not the API.
  • Parsed version: ParseError: user.id: expected string, got number at the fetch wrapper, before any component mounts, naming the field.

Failure modes worth naming.

  1. fetch resolves on 404. It only rejects on network failure, so res.json() happily parses an error body and your parser reports a missing field instead of a 404. Check res.ok before parsing.
  2. any leaking past the cast. noImplicitAny doesn't see it: the any came from a declaration, not an inference. @typescript-eslint/no-unsafe-assignment and no-unsafe-member-access do.
  3. Validating only today's fields. Add avatarUrl to the UI next sprint and it's read straight off the raw object. Keep the parse function the only place the wire shape is touched; grep for .json() in review.
  4. null vs undefined. A server that sends email: null against email?: string type-checks and then fails an email !== undefined guard. Under strictNullChecks they are different types; pick one and encode it.
ApproachCompiler checksRuntime costType/check drift
as Usernothingnonesilent, forever
Hand-written guardthe guard bodyone pass per responseonly if you edit both
Schema library (zod, valibot)the schema; type via z.inferone pass + a dependency (zod v3 core is roughly 13 kB min+gzip)impossible between type and schema; still possible against the server

When not to parse. If the type is generated from the server's own definition (OpenAPI codegen, GraphQL codegen, tRPC) the contract is already machine-derived and a hand-written parser is duplicated work. Same for a throwaway script. The rule is about who owns the type: if a human typed it, a runtime check has to back it.

Curated: · Written: · Reviewed:

Q&A-21

A dependency you need ships no types. Walk me through your options (`@types/*`, a hand-written declaration file, `declare module`, module augmentation) and when each is the right call?

Answer

The 90-second answer. Check first whether the package ships its own types: a types or typings field in its package.json, or an index.d.ts beside the entry. If it does, you're done: for import x from 'foo', TypeScript resolves node_modules/foo before node_modules/@types/foo. If it doesn't, the ladder is: install @types/foo from DefinitelyTyped; if that doesn't exist, write a local declaration file; if you touch the package in one or two places, wrap it behind your own typed module instead of declaring its whole surface. The one option I'd refuse is the bodyless declare module 'foo';: it types the whole package as any and silently disables checking at every call site, with no error to notice.

Resolution, precisely. The types array in tsconfig only controls automatic global inclusion of @types/* packages. "types": [] does not break import React from 'react', because that is module resolution, not a global include. typeRoots changes where the @types folder is searched for.

SituationMoveWhat it costs you
Ships types/typingsnothing—
DefinitelyTyped has itnpm i -D @types/fooseparate release train from the runtime package
No types, small surfacehand-written .d.tsyou own it, and it drifts
No types, used in 2 placeswrap it in your own typed moduleone indirection
No types, large surfacefull declare module with real signatures, or contribute to DTeffort, and a maintenance commitment

A hand-written ambient declaration. It must live in a script file, no top-level import/export, or the declaration is treated as an augmentation instead:

// src/types/legacy-chart.d.ts  (no top-level import/export)
declare module 'legacy-chart' {
  export interface ChartOptions {
    width: number;
    height: number;
    theme?: 'light' | 'dark';
  }
  export function render(el: HTMLElement, opts: ChartOptions): () => void;
  export default render;
}

// src/types/assets.d.ts — the wildcard form, for non-code imports
declare module '*.svg' {
  const src: string;
  export default src;
}

Module augmentation is the other direction: the package has types and you need to add to them. It must be in a module file (top-level import/export), and it can only patch existing declarations: you cannot add new top-level exports this way.

// src/types/router-augment.ts
import 'react-router-dom';            // this import is what makes it an augmentation

declare module 'react-router-dom' {   // react-router-dom v6 exports NavigateFunction
  interface NavigateFunction {        // as an interface, so it merges
    toExternal(url: string): void;
  }
}

Failure modes, and how you catch each.

  1. Bodyless ambient module. declare module 'foo'; makes every import any. noImplicitAny does not fire, because the type is explicitly any. Detect: grep -rn "declare module '[^']*';" src/ in CI and require every hit to have a body.
  2. Augmentation in a script file. No top-level import means it is an ambient declaration, not a merge: the augmentation silently has no effect at the call site, or you get a duplicate-identifier error. Detect: tsc --noEmit plus one assertion that the added member is actually visible.
  3. Version skew. @types/react majors track React majors, and DefinitelyTyped ships on its own schedule. @types/react@18 against react@19 gives prop types that don't match the docs, or Cannot find module 'react' or its corresponding type declarations. Detect: pin @types/* majors to the runtime major and assert it in CI.
  4. skipLibCheck: true (the default in most Vite and Next templates) skips checking of all .d.ts files, including the one you just wrote. A wrong signature in your own declaration file is never reported. Detect: run tsc --noEmit --skipLibCheck false over src/types/ in CI, and keep hand-written declarations small enough to read.
  5. Drift. The package adds a required option, your .d.ts still marks it optional, and the runtime throws. Detect: one smoke test that calls the real package through the typed wrapper.

For a single bad call site, // @ts-expect-error beats // @ts-ignore: it fails the build once the underlying error disappears, so it cleans itself up.

Curated: · Written: · Reviewed:

Q&A-23

Your Vite build is green but `tsc --noEmit` fails on a type-only re-export. Walk me through what the bundler did with your types, what `isolatedModules` and `verbatimModuleSyntax` enforce, and why the type-check runs as a separate CI job.

Answer

The 90-second answer. Types are erased, never executed, and erasing and checking are two different jobs done by two different tools. Vite transforms with esbuild, Next.js with SWC, a Babel setup with @babel/preset-typescript; all three work one file at a time with no type information, so none of them can tell a type from a value. tsc builds the whole program, follows every import, and reports errors: it is the only thing in the chain that does. So the pipeline is: the bundler emits JavaScript fast, tsc --noEmit runs as its own CI job, and the two run in parallel.

ToolType-checksUnit of workEmits .d.ts
tscyeswhole programyes
esbuild (Vite)noone fileno
SWC (Next.js)noone fileno
@babel/preset-typescriptnoone fileno

What breaks without isolatedModules. A per-file transpiler sees export { User, MAX } from './types' and cannot know User is a type. It keeps the export, and at runtime the module throws or exports undefined. isolatedModules: true makes tsc reject exactly the constructs that need cross-file knowledge:

// types.ts
export type User = { id: string; name: string };
export const MAX = 10;

// index.ts
export { User, MAX } from './types';
// TS1205: Re-exporting a type when 'isolatedModules' is enabled
// requires using 'export type'.

export type { User } from './types';   // fine
export { MAX } from './types';         // fine

It also flags ambient const enum access (TS2748). esbuild can inline a const enum declared in the same file but not one imported from another, so the values silently diverge between files. Use a const object plus a union of keyof typeof instead.

What verbatimModuleSyntax adds. TS 5.0. Every import and export is emitted exactly as written, with no elision, so a type imported without the type modifier becomes a runtime import of a binding that does not exist:

import { User } from './types';            // TS1484 under verbatimModuleSyntax
import type { User } from './types';       // erased entirely
import { type User, MAX } from './types';  // inline form, TS 4.5+

It replaces importsNotUsedAsValues and preserveValueImports, both removed in 5.5. Turn both flags on: isolatedModules is the floor any bundler needs, verbatimModuleSyntax is what keeps the source honest about which imports are real.

Why the check is a separate job. Type-checking is whole-program and cannot be incremental per file the way a transform is. Illustrative numbers for a 1,800-file app: esbuild transform ~1.5 s, cold tsc --noEmit ~35 s, incremental with .tsbuildinfo ~4 s. Run them as parallel CI jobs so a type error fails the PR without blocking a preview deploy, and keep skipLibCheck: true: checking node_modules .d.ts files is usually the single largest cost.

typecheck:  npx tsc --noEmit
build:      npx vite build

Two traps. Vite's react-ts template chains tsc -b && vite build, serialising the slow step behind the fast one; split it. And Next.js type-checks inside next build by default: teams that set typescript.ignoreBuildErrors: true for build speed often never add the standalone tsc job, and the types go unchecked. Libraries need tsc --emitDeclarationOnly regardless: nothing else in that table produces .d.ts.

Curated: · Written: · Reviewed:

Q&A-22

Walk me through why a deeply recursive conditional type slows `tsc` down, how you'd measure it, and when you'd simplify the type.

Answer

The 90-second answer. Type-level code is code the checker runs. A recursive conditional type is a loop, and TypeScript's loop is unrolled: every level of recursion, and every member of a union it distributes over, produces a new type instantiation that gets cached and then compared against others for assignability. Cost is roughly linear in instantiations and superlinear in check time, because the relation caches grow with the number of distinct types. So the question isn't "is this type clever", it's "how many instantiations does it cost on the real input, and does that show up in Check time".

Measure with tsc -p tsconfig.app.json --extendedDiagnostics. The lines that matter:

Types:                      1240338
Instantiations:             4802117
Assignability cache size:   318442
Check time:                  14.62s
Total time:                  16.11s

Instantiations is the counter to watch; Check time is what the team feels. Compare against a baseline on the same machine and the same TypeScript version: these numbers are not portable.

When Instantiations is high and you don't know which type is responsible, tsc --generateTrace traceDir writes trace.json and types.json. types.json lists every type with a count:

jq -r '.types | sort_by(-.count) | .[0:5][] | "\(.count)\t\(.display)"' traceDir/types.json
48213   DeepPartial<ApiSchema>
12044   Paths<Config>
 3901   DeepPartial<ApiSchema["user"]>

That's the answer: one type, instantiated 48k times. Delete the .tsbuildinfo first, or the build is a no-op and the trace is empty.

Why it explodes. Take the standard DeepPartial:

type DeepPartial<T> = T extends (infer U)[]
  ? DeepPartial<U>[]
  : T extends object
    ? { [K in keyof T]?: DeepPartial<T[K]> }
    : T;

Three things multiply. The conditional distributes over naked T, so a union of 40 members costs 40 instantiations per level. The mapped type instantiates once per key, so a 400-key schema costs 400 per level. And the recursion isn't in tail position, DeepPartial<U>[] wraps the recursive call, so TypeScript 4.5's tail-recursion elimination doesn't apply, and the checker caps instantiation depth at 100 and total instantiations at 5,000,000. Crossing either gives Type instantiation is excessively deep and possibly infinite, which is the good outcome: a loud error instead of a 90-second build.

The fix, in order of preference. First, don't compute it: if the type only exists to describe a public API, hand-write the interface. Interfaces are lazy, the checker doesn't expand them until it has to, while a recursive type alias is resolved on reference. Second, cap the depth:

type Prev = [never, 0, 1, 2, 3, 4, 5];
type DeepPartial<T, D extends number = 5> = [D] extends [never]
  ? T
  : T extends (infer U)[]
    ? DeepPartial<U, Prev[D]>[]
    : T extends object
      ? { [K in keyof T]?: DeepPartial<T[K], Prev[D]> }
      : T;

Third, narrow the input: DeepPartial<Pick<ApiSchema, 'user' | 'billing'>> instead of the whole schema.

Failure modes. The type is cheap on the three-field fixture in the test suite and catastrophic on the generated 400-key schema, so CI stays green while the build takes 15 seconds: measure on the real project. --extendedDiagnostics measures tsc, not the language service, so a type can be fine in CI and still make autocomplete unusable in the editor; check the TS Server log separately. And --generateTrace on a large repo writes a trace.json measured in gigabytes: run it on a repro, never in CI.

Curated: · Written: · Reviewed:

Q&A-25

A colleague's `(e: MouseEvent) => void` handler is rejected where `(e: Event) => void` is expected, yet the identical signature declared as a method compiles. Explain the variance rule behind both, and which one is hiding a bug?

Answer

The 90-second answer. Under strictFunctionTypes, on by default with strict: true, parameter positions are checked contravariantly: a function is assignable to another only if its parameters are wider or equal. A handler that demands MouseEvent cannot stand in for one that promises to accept any Event, because the caller may hand it a keyboard event and the handler will read clientX off it. That rejection is correct; it is the compiler catching a real bug.

Method syntax is exempt. TypeScript checks parameters of a method declaration bivariantly, so the same signature written as handle(e: MouseEvent): void accepts the unsafe direction silently.

ts // TypeScript 5.4, strict: true type FnHandler = (e: MouseEvent) => void; interface MethodHandler { handle(e: MouseEvent): void }

declare const fn: FnHandler; declare const method: MethodHandler;

const a: (e: Event) => void = fn; // error 2322 const b: { handle(e: Event): void } = method; // compiles

The error reads Types of parameters 'e' and 'e' are incompatible: the compiler names the parameter types, not the return type, because that is where the mismatch is.

The safe direction compiles, and it is worth knowing why:

ts declare const general: (e: Event) => void; const m: (e: MouseEvent) => void = general; // OK. Event is wider than MouseEvent

Where this bites in React. MouseEventHandler<T> is declared as a property, (event: MouseEvent<T>) => void, so it is contravariant. A handler annotated for a button cannot be reused on a div:

tsx const onClick = (e: React.MouseEvent<HTMLButtonElement>) => e.currentTarget.disabled; <button onClick={onClick} />; // fine

<div onClick={onClick} />; // error: MouseEvent<HTMLDivElement> not assignable to MouseEvent<HTMLButtonElement>

That error is the point: currentTarget on a div has no disabled. Widen the parameter to React.MouseEvent<HTMLElement> and narrow inside, or keep the handler button-specific and stop reusing it.

The same bug through a method. Hand-written port interfaces often use method syntax, and there the check disappears:

ts interface Narrow { handle(e: React.MouseEvent<HTMLButtonElement>): void } interface Wide { handle(e: React.MouseEvent<HTMLElement>): void }

declare const narrow: Narrow; const wide: Wide = narrow; // compiles. Bivariance takes the unsafe direction

Change handle to a property (handle: (e: ...) => void) and the same assignment errors.

DeclarationParameter check(e: MouseEvent) => void where (e: Event) => void is expected
handle: (e: MouseEvent) => voidcontravariantrejected
handle(e: MouseEvent): voidbivariantaccepted

Why the exemption exists. The strictFunctionTypes release notes say stricter checks broke a large number of inherently unsafe class hierarchies, notably in the DOM. The same exemption is what keeps Array<Dog> assignable to Array<Animal>: push is a method, and contravariant checking would reject it. The cost is that Array<Animal>.push will happily take a Cat.

Failure modes. The narrow handler reaches production and reads a property that does not exist on the actual event or element: undefined, not a crash, so it fails quietly. Detect it with a test that dispatches the wider event (a keydown into a handler typed for MouseEvent), or by turning the method into a property so the compiler reports it. Casting with as to silence the error removes the check and keeps the bug.

Return positions go the other way, covariant, and a void return type accepts a function returning anything, which is why onClick={() => setOpen(true)} type-checks.

Curated: · Written: · Reviewed: