Skip to main content
Frontend & Core Web

TypeScript Interview Questions

All Levels (Junior to Staff)16 Questions

Master TypeScript structural typing, generic constraints, conditional types, mapped types, covariance and contravariance, and compiler performance tuning.

22 min study timeIncludes Production Code & Pitfall TrapsActive Recall Practice Mode Available

Practice TypeScript Interview Questions

Showing 16 of 16 technical questions with engineering explanations

Filter Level:
Question #1FundamentalJunior

How do 'unknown', 'any', and 'never' differ in TypeScript's type lattice?

Senior Engineering Answer

'unknown' is the type-safe top type: any value can be assigned to unknown, but TypeScript forbids reading properties or calling methods on it until you narrow it via typeof, instanceof, or a type guard. 'any' opts out of type checking completely—it is assignable to and from everything, silently propagating unsafety across callers. 'never' is the bottom type representing an empty set of values: a function that always throws or loops forever returns never, and an unreachable switch branch narrows to never.

Production Code Example
function parseJson(raw: string): unknown {
  return JSON.parse(raw);
}

const data = parseJson('{"port": 8080}');
if (typeof data === "object" && data !== null && "port" in data) {
  console.log(data.port); // narrowed safely
}
Common Interview Trap / Anti-Pattern:

Typing JSON.parse() or catch(err) as 'any' disables compiler checks downstream; with useUnknownInCatchVariables enabled (default in strict mode), catch errors are typed as unknown.

Question #2FundamentalJunior

When should you prefer an 'interface' over a 'type' alias, and vice versa?

Senior Engineering Answer

Interfaces describe object/class shapes, support 'extends', and participate in declaration merging (two interface declarations with the same name in the same scope merge automatically, which is essential for augmenting third-party library types). Type aliases can express anything interfaces cannot: unions, intersections, primitives, tuples, conditional types, and mapped types. For large object hierarchies, 'interface extends' is also slightly faster for tsc to cache and check than '&' intersections.

Production Code Example
interface ApiError {
  code: number;
  message: string;
}

type Result<T> =
  | { ok: true; value: T }
  | { ok: false; error: ApiError };
Common Interview Trap / Anti-Pattern:

An interface cannot be directly assigned to a Record<string, unknown> parameter unless it has an explicit index signature, because another declaration might merge onto the interface later; type aliases for plain objects have implicit index signature compatibility.

Question #3FundamentalJunior

How do discriminated unions and exhaustiveness checking with 'never' prevent missing case bugs?

Senior Engineering Answer

A discriminated union combines object types sharing a common literal discriminant property (such as 'kind' or 'status'). Narrowing on the discriminant inside an if/switch lets TypeScript infer the exact payload fields of each variant. Adding a default branch that passes the remaining value to an 'assertNever(x: never)' helper causes a compile-time error the moment a developer adds a new union variant without handling it.

Production Code Example
type JobState =
  | { status: "pending" }
  | { status: "done"; url: string }
  | { status: "failed"; reason: string };

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

function renderStatus(state: JobState): string {
  switch (state.status) {
    case "pending": return "Queued";
    case "done": return state.url;
    case "failed": return state.reason;
    default: return assertNever(state);
  }
}
Common Interview Trap / Anti-Pattern:

If a switch function lacks a default assertNever guard and does not specify an explicit return type, adding a new union member silently returns undefined at runtime without a compiler error.

Question #4FundamentalJunior

What does an 'as const' assertion do compared to a standard 'const' declaration?

Senior Engineering Answer

A standard 'const' binding prevents reassigning the variable, but TypeScript still widens object properties and array elements to mutable general types (e.g., string, number[]). Appending 'as const' makes every nested property deeply readonly and narrows all primitives to their exact literal types and arrays to readonly tuples. This is essential for deriving union types from runtime configuration arrays or Redux/reducer action tuples.

Production Code Example
const ROLES = ["admin", "editor", "viewer"] as const;
type Role = (typeof ROLES)[number]; // "admin" | "editor" | "viewer"

const config = {
  env: "prod",
  ports: [80, 443]
} as const;
// config.env is "prod", config.ports is readonly [80, 443]
Common Interview Trap / Anti-Pattern:

Passing an 'as const' array to a function expecting a mutable 'string[]' fails to compile; accept 'readonly string[]' on read-only utility parameters.

Question #5IntermediateMid

How do generic constraints (extends), keyof, and indexed access types (T[K]) preserve exact property types?

Senior Engineering Answer

By constraining a key type parameter K with 'K extends keyof T', TypeScript restricts callers to keys that actually exist on T. Using the indexed access type 'T[K]' as the return type preserves the exact value type corresponding to the specific key K passed at the call site rather than widening to a union of all property values.

Production Code Example
function pluck<T, K extends keyof T>(items: readonly T[], key: K): T[K][] {
  return items.map((item) => item[key]);
}

const users = [{ id: 1, name: "Ada" }, { id: 2, name: "Lin" }];
const names = pluck(users, "name"); // string[]
// pluck(users, "email"); // Compile error: Argument of type '"email"' is not assignable
Common Interview Trap / Anti-Pattern:

Remember that 'keyof' on an object union returns only the intersection of keys shared across all union members, not the union of all keys.

Question #6IntermediateMid

How does the 'satisfies' operator differ from a type annotation (:) and a type assertion (as)?

Senior Engineering Answer

A type annotation (const palette: Record<string, string | number[]>) validates the value against the contract, but widens the variable's inferred type to the annotation, losing specific keys and literal/tuple knowledge. A type assertion ('as') overrides the compiler and can hide missing or invalid properties. The 'satisfies' operator validates that the expression conforms to the target type at compile time while keeping the narrowest inferred literal type of the expression itself.

Production Code Example
type ColorMap = Record<"red" | "green" | "blue", string | [number, number, number]>;

const palette = {
  red: [255, 0, 0],
  green: "#00ff00",
  blue: [0, 0, 255]
} satisfies ColorMap;

// TypeScript knows palette.green is string and palette.red is number[]!
const hex = palette.green.toUpperCase();
const r = palette.red[0] + 1;
Common Interview Trap / Anti-Pattern:

Using 'as ColorMap' suppresses missing key errors and allows typos; never use 'as' where 'satisfies' or a proper annotation can verify the expression.

Question #7IntermediateMid

What is the difference between a custom type predicate ('x is T') and an assertion function ('asserts x is T')?

Senior Engineering Answer

A type predicate function returns a boolean ('function isUser(v: unknown): v is User') and narrows the argument only inside the truthy branch of a conditional (and the falsy branch when applicable). An assertion function ('function assertUser(v: unknown): asserts v is User') returns void and throws an Error if the invariant fails, narrowing the variable for the remainder of the enclosing scope after the call without needing an if-block. Note that TypeScript requires assertion functions to be declared with a function declaration or an explicit type annotation—arrow expressions without an explicit type annotation will not act as assertion signatures.

Production Code Example
interface User { id: string; email: string }

function isUser(v: unknown): v is User {
  return typeof v === "object" && v !== null && "id" in v && "email" in v;
}

function assertNonNull<T>(v: T, msg: string): asserts v is NonNullable<T> {
  if (v == null) throw new Error(msg);
}

function sendWelcome(maybeUser: User | null) {
  assertNonNull(maybeUser, "Missing user");
  return maybeUser.email; // narrowed to User
}
Common Interview Trap / Anti-Pattern:

TypeScript does NOT verify the runtime logic inside a 'v is T' predicate; returning true carelessly lies to the type checker just like an 'as' cast.

Question #8IntermediateMid

Why does Omit<T, K> sometimes allow typos in K, and how do you build a StrictOmit<T, K>?

Senior Engineering Answer

Standard TypeScript Omit<T, K> is defined as Pick<T, Exclude<keyof T, K>>, where K is constrained only to 'keyof any' (string | number | symbol), not 'keyof T'. Passing a misspelled key like Omit<User, 'emial'> compiles silently without dropping 'email'. Defining 'type StrictOmit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>' forces K to be a real key of T. Similarly, note that standard Pick/Omit operate non-distributively on union types unless mapped over 'T extends unknown'.

Production Code Example
type StrictOmit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;

interface Account { id: string; secretHash: string; role: string }
type PublicAccount = StrictOmit<Account, "secretHash">;
// StrictOmit<Account, "secret"> // Compile error: '"secret"' not in keyof Account
Common Interview Trap / Anti-Pattern:

Applying Omit<UnionType, 'id'> collapses a discriminated union into only the common keys across all variants instead of omitting 'id' from each variant; wrap it in a distributive conditional type 'T extends unknown ? Omit<T, K> : never' for unions.

Question #9SeniorSenior

How do distributive conditional types and the 'infer' keyword work, and how do you prevent unwanted distribution?

Senior Engineering Answer

When a conditional type checks a naked type parameter (e.g., 'T extends U ? X : Y') and T is a union 'A | B', TypeScript distributes the condition across each union member individually and unions the results: '(A extends U ? X : Y) | (B extends U ? X : Y)'. Wrapping both sides in a single-element tuple ('[T] extends [U]') stops distribution so the union is tested as a whole. Inside the extends clause, 'infer R' introduces a pattern-matched type variable extracted from promises, function parameters, or string patterns.

Production Code Example
type UnwrapPromise<T> = T extends Promise<infer U> ? UnwrapPromise<U> : T;
type Val = UnwrapPromise<Promise<Promise<number>>>; // number

// Disable distribution to test if the entire union equals a target
type IsUnion<T, Copy = T> = T extends unknown
  ? [Copy] extends [T] ? false : true
  : never;
type Test1 = IsUnion<string | number>; // true
type Test2 = IsUnion<string>;          // false
Common Interview Trap / Anti-Pattern:

Forgetting that 'T extends U' distributes when T is a naked generic parameter causes subtle bugs when checking 'T extends string[]' on 'string | string[]' or when T is 'never' (which distributes to 'never' immediately!).

Question #10SeniorSenior

How do mapped types with 'as' key remapping and template literal types let you transform object APIs cleanly?

Senior Engineering Answer

Mapped types iterate over keys '[K in keyof T]: ...', optionally adding or stripping modifiers (+readonly, -readonly, +?, -?). Adding an 'as' clause remaps or filters keys (returning 'never' omits a key), and template literal types combine Capitalize/Uncapitalize/Uppercase/Lowercase intrinsics to generate derived method or event handler names at compile time.

Production Code Example
type Getters<T> = {
  [K in keyof T as K extends string ? `get${Capitalize<K>}` : never]: () => T[K];
};

interface Config { host: string; port: number }
type ConfigGetters = Getters<Config>;
// { getHost: () => string; getPort: () => number }
Common Interview Trap / Anti-Pattern:

Intersecting 'keyof T' directly inside a template literal fails unless you constrain 'K extends string' (or 'string & keyof T') because 'keyof T' can include symbols, which cannot appear inside template literal types.

Question #11SeniorSenior

Explain covariance and contravariance in TypeScript, and why method syntax behaves differently from function property syntax under strictFunctionTypes.

Senior Engineering Answer

A type constructor is covariant if it preserves subtype direction (Dog <: Animal implies Producer<Dog> <: Producer<Animal>, such as return types and readonly arrays). Function parameters are contravariant under 'strictFunctionTypes': Dog <: Animal implies Consumer<Animal> <: Consumer<Dog>, because a callback expecting an Animal can safely accept any Dog. Crucially, TypeScript checks parameters contravariantly ONLY for function-typed properties ('onClick: (e: Event) => void') and leaves shorthand interface methods ('onClick(e: Event): void') bivariant intentionally for backward compatibility with standard library types like Array<T>.push.

Production Code Example
interface Event { timestamp: number }
interface MouseEvent extends Event { clientX: number }

interface SafeHandler {
  handle: (e: MouseEvent) => void; // contravariant under strictFunctionTypes
}

const genericLogger = (e: Event) => console.log(e.timestamp);
const ok: SafeHandler = { handle: genericLogger }; // OK: Event handler handles MouseEvent

const mouseOnly = (e: MouseEvent) => console.log(e.clientX);
// Assigning mouseOnly where (e: Event) => void is expected is rejected when declared as a property!
Common Interview Trap / Anti-Pattern:

Declaring callback fields in interfaces using method shorthand ('onEvent(e: SubEvent): void') silently opts out of strictFunctionTypes contravariance checking; use function property syntax ('onEvent: (e: SubEvent) => void') for strict callbacks.

Question #12SeniorSenior

How do you prevent accidentally mixing structurally identical primitives (like UserId vs OrderId) in TypeScript?

Senior Engineering Answer

Because TypeScript uses structural typing, two type aliases 'type UserId = string' and 'type OrderId = string' are completely interchangeable. To enforce nominal separation with zero runtime overhead, use branded (opaque) types by intersecting the primitive with an optional or phantom property keyed by a 'unique symbol' or literal tag. Validation functions act as constructors returning the branded type.

Production Code Example
declare const brand: unique symbol;
type Brand<T, Name extends string> = T & { readonly [brand]: Name };

type UserId = Brand<string, "UserId">;
type OrderId = Brand<string, "OrderId">;

const asUserId = (id: string): UserId => id as UserId;
function loadOrders(uid: UserId) { return uid; }

const orderId = "ord_1" as OrderId;
// loadOrders(orderId); // Compile error: Branded types are incompatible
Common Interview Trap / Anti-Pattern:

Using an un-namespaced string key like '{ __brand?: "UserId" }' as an optional property can still allow plain object spreads or accidental assignment; using a 'declare const brand: unique symbol' non-optional phantom property makes accidental construction impossible.

Question #13PrincipalStaff

Which strict TypeScript compiler flags catch real production bugs beyond 'strict: true', and when does moduleResolution 'bundler' vs 'nodenext' matter?

Senior Engineering Answer

'strict: true' omits two high-value safety checks: 'noUncheckedIndexedAccess' (adds '| undefined' to array/Record index reads like arr[0] or dict[key]) and 'exactOptionalPropertyTypes' (prevents assigning explicit 'undefined' to 'prop?: string', distinguishing missing keys from undefined values). For module resolution, 'nodenext' enforces Node's ESM package.json 'exports' rules and explicit file extensions (./foo.js), which is vital for published libraries and Node services; 'bundler' enforces package.json 'exports' while allowing extensionless imports for Vite, Next.js, and esbuild apps.

Production Code Example
// With noUncheckedIndexedAccess: true
const scores: Record<string, number> = { alice: 10 };
const bob = scores["bob"]; // type is number | undefined
if (bob !== undefined) {
  console.log(bob.toFixed(1));
}
Common Interview Trap / Anti-Pattern:

Publishing an npm package compiled with moduleResolution: 'bundler' and extensionless relative imports breaks downstream consumers running Node ESM ('nodenext') directly.

Question #14PrincipalStaff

How do you build a zero-overhead, end-to-end typed event emitter or RPC client using variadic tuple types and mapped event contracts?

Senior Engineering Answer

Define a central EventMap interface mapping event names to payload tuples (or parameter lists), then constrain emit/on with 'K extends keyof EventMap' and rest-spread variadic args '...args: EventMap[K]'. This lets single-argument, multi-argument, and zero-argument events share one strictly typed API without function overloads.

Production Code Example
type EventMap = {
  connected: [host: string, port: number];
  closed: [];
  error: [err: Error];
};

class TypedEmitter<Events extends Record<string, unknown[]>> {
  private listeners: { [K in keyof Events]?: Array<(...args: Events[K]) => void> } = {};

  on<K extends keyof Events>(event: K, fn: (...args: Events[K]) => void): void {
    (this.listeners[event] ??= []).push(fn);
  }

  emit<K extends keyof Events>(event: K, ...args: Events[K]): void {
    this.listeners[event]?.forEach((fn) => fn(...args));
  }
}

const bus = new TypedEmitter<EventMap>();
bus.on("connected", (host, port) => console.log(host, port));
bus.emit("closed");
Common Interview Trap / Anti-Pattern:

Indexing 'this.listeners[event]' with generic K inside emit often yields union errors when writing to the map unless you encapsulate listener storage carefully or avoid mixing generic writes with covariant reads.

Question #15PrincipalStaff

How do you diagnose and fix slow TypeScript type-checking and IDE lag in a large monorepo?

Senior Engineering Answer

Run 'tsc --generateTrace traceDir' (and '@typescript/analyze-trace') plus 'tsc --extendedDiagnostics' to pinpoint expensive files, type instantiations, and check times. Root causes are almost always: (1) missing Project References ('composite: true', 'declarationMap: true', 'tsc -b') forcing every package to re-check transitive sources instead of cached .d.ts files, (2) massive union/intersection types or deeply recursive conditional types (such as giant router/ORM schemas) exhausting instantiation caches, and (3) preferring '&' type intersections over 'interface extends', which prevents tsc from caching named object type relationships.

Production Code Example
// Prefer interface extends over '&' for large domain models
interface BaseEntity { id: string; createdAt: Date }
interface Invoice extends BaseEntity { totalCents: number }

// In tsconfig.json for monorepo subpackages:
// { "compilerOptions": { "composite": true, "incremental": true, "declaration": true } }
Common Interview Trap / Anti-Pattern:

Explicitly omitting return type annotations on exported functions in monorepo packages forces TypeScript to infer and serialize huge inferred structural types into .d.ts files, exploding cross-package type-check latency.

Question #16PrincipalStaff

Why are TypeScript types insufficient at network and I/O boundaries, and how do you unify compile-time types with runtime validation?

Senior Engineering Answer

TypeScript types are completely erased during compilation to JavaScript—an API response cast as 'res.json() as User' performs zero runtime verification and will pass corrupted shapes into business logic until deep code crashes on undefined property access. Schema-first libraries like Zod, Valibot, or TypeBox define a single runtime parser from which the TypeScript type is statically inferred ('z.infer<typeof UserSchema>'), guaranteeing runtime payloads and compile-time types never drift apart.

Production Code Example
// Schema-first pattern (mirrors Zod/Valibot architecture)
type Infer<S> = S extends { parse: (v: unknown) => infer T } ? T : never;

const CreateOrderSchema = {
  parse(input: unknown): { sku: string; qty: number } {
    if (typeof input !== "object" || input === null) throw new Error("Invalid payload");
    const obj = input as Record<string, unknown>;
    if (typeof obj.sku !== "string" || typeof obj.qty !== "number" || obj.qty < 1) {
      throw new Error("Invalid order fields");
    }
    return { sku: obj.sku, qty: obj.qty };
  }
};

type CreateOrderInput = Infer<typeof CreateOrderSchema>;
Common Interview Trap / Anti-Pattern:

Maintaining separate TypeScript interfaces and manual validation schemas in parallel inevitably leads to silent drift where a required field is added to the interface but missed in the runtime validator.

TypeScript Track Coverage & Difficulty Profile

16 of 16 prompts include code examples

This TypeScript preparation set groups 16 prompts across Junior (4), Mid (4), Senior (4), Staff (4) roles with 4 fundamental, 4 intermediate, 4 senior, 4 principal exercises tailored to Frontend & Core Web.

JuniorFundamental

How do 'unknown', 'any', and 'never' differ in TypeScript's type lattice?

JuniorFundamental

When should you prefer an 'interface' over a 'type' alias, and vice versa?

JuniorFundamental

How do discriminated unions and exhaustiveness checking with 'never' prevent missing case bugs?

JuniorFundamental

What does an 'as const' assertion do compared to a standard 'const' declaration?

MidIntermediate

How do generic constraints (extends), keyof, and indexed access types (T[K]) preserve exact property types?

MidIntermediate

How does the 'satisfies' operator differ from a type annotation (:) and a type assertion (as)?

Frequently Asked Technical Interview Questions (TypeScript)

Essential theoretical concepts, architecture trade-offs, and runtime design questions asked by hiring committees.

What is the difference between Type Aliases and Interfaces in TypeScript?
Interfaces support declaration merging and 'extends' inheritance for object contracts, while type aliases can represent unions, tuples, primitives, conditional types, and mapped types that interfaces cannot express.
How does the 'infer' keyword work inside conditional types?
Inside the 'extends' clause of a conditional type, 'infer U' binds a pattern-matched inner type (such as the resolved value of Promise<infer U> or return type of a function) so it can be returned in the true branch.
What is the difference between 'unknown', 'any', and 'never'?
'any' disables type checking completely. 'unknown' is the type-safe top type that accepts any value but requires narrowing before use. 'never' is the bottom type representing impossible values or functions that never return normally.
How does the 'satisfies' operator prevent unwanted type widening?
'satisfies' verifies that an expression conforms to a target type contract at compile time without widening the inferred literal and tuple types of the expression itself.
Complete Learning Ecosystem

Pair Interview Prep with Cheat Sheets & Roadmaps

Review syntax formulas on our interactive cheat sheets, test your skills in technical quizzes, and study high-scale system designs.

Want to practice other technologies?

Explore our comprehensive technical interview tracks across all core technology stacks.

Browse All Interview Tracks