TypeScript Middle cheat sheet: interview answers

Every question of this level with its correct answer and explanation, on one page for a quick review before the interview.

Quick reference: Key concepts and pitfalls on a couple of pages →
  1. 1. What is a user-defined type guard?

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

    Correct answer: A function with the return type x is T that narrows the argument when true

    After if (isUser(data)), data has type User inside the branch. The developer is responsible for the check being correct: the compiler trusts the predicate. Since TS 5.5, simple predicates are inferred automatically, e.g. for arr.filter(x => x !== null).

  2. 2. How do you guarantee that a switch handled every member of a union?

    function area(s: Shape) {
      switch (s.kind) {
        case 'circle': return Math.PI * s.radius ** 2;
        case 'square': return s.size ** 2;
        default: { const _exhaustive: never = s; return _exhaustive; }
      }
    }

    Correct answer: Assign the value in default to a variable of type never

    If you add a new shape to Shape and forget a case, a non-empty type remains in default, and assigning it to never causes a compile error. The noImplicitReturns flag and the ESLint rule switch-exhaustiveness-check also help.

  3. 3. What does <T extends { id: string }> mean in a generic?

    Correct answer: A constraint: T must have at least an id: string property

    A constraint lets you safely access item.id inside the function while keeping the full type T in the result. You can pass any object with a suitable id and other fields. Classes and inheritance have nothing to do with it.

  4. 4. How do you type getProp(obj, key) so the result depends on the key?

    Correct answer: function getProp<T, K extends keyof T>(obj: T, key: K): T[K]

    K extends keyof T allows only existing keys, and the indexed access T[K] gives the exact value type: getProp(user, 'age') → number. The any version loses typing, and string lets typos through.

  5. 5. What is a mapped type?

    type Flags<T> = { [K in keyof T]: boolean };

    Correct answer: A type that creates new properties by iterating over another type's keys

    [K in keyof T] iterates over the keys. You can change the value type, add or remove modifiers (readonly, ?, -?) and rename keys with as. Partial, Readonly and Record are built on mapped types.

  6. 6. What does the conditional type T extends string ? 'text' : 'other' do?

    Correct answer: Picks one of the types depending on whether T is assignable to string

    Conditional types are a type-level "ternary". Together with infer, they let you extract parts of types. Applied to a union, they distribute over each member (distributive conditional types).

  7. 7. What does infer do in type ElementType<T> = T extends (infer U)[] ? U : never?

    Correct answer: Declares a type variable U that TS infers from matching the pattern

    infer is used only in the extends part of a conditional type: TS matches T against the pattern and "captures" the needed part. ElementType<string[]> → string. That's how ReturnType, Parameters and Awaited work.

  8. 8. What does Awaited<Promise<Promise<number>>> return?

    Correct answer: number

    Awaited recursively unwraps promises and thenables, mirroring the behavior of await. Handy for an async function's result type: Awaited<ReturnType<typeof fetchUser>>.

  9. 9. How does Exclude<T, U> differ from Omit<T, K>?

    Correct answer: Exclude removes members from a union, Omit removes properties from an object type

    Exclude<'a' | 'b' | 'c', 'a'> → 'b' | 'c'. Omit<User, 'password'> → an object without the field. Paired utilities: Extract (keep matching union members) and Pick (keep properties). NonNullable<T> removes null and undefined.

  10. 10. How do function overloads work in TypeScript?

    function parse(x: string): number;
    function parse(x: number): string;
    function parse(x: string | number) { /* ... */ }

    Correct answer: Several call signatures and one hidden implementation

    Calling code sees only the overload signatures, and TS picks the first matching one from top to bottom. The implementation must be compatible with all of them. Overloads can often be replaced with a union parameter or a generic with a conditional type.

  11. 11. What is declaration merging?

    Correct answer: Combining same-named declarations, e.g. two interface Windows, into one

    Interfaces, namespaces and some other declarations with the same name merge. That's how global types are extended: interface Window { analytics: Analytics } in declare global. type aliases don't merge - redeclaring one is an error.

  12. 12. What is an abstract class for?

    Correct answer: A shared base with abstract methods, not instantiable

    abstract class Repo { abstract find(id): T; log() {...} } - subclasses must implement find and get log ready-made. Unlike an interface, an abstract class exists at runtime and can contain code and state.

  13. 13. How does protected differ from private in TypeScript classes?

    Correct answer: protected is open to subclasses, private isn't

    public (the default) is accessible everywhere, protected in the class and its subclasses, private only in the declaring class. All three are compiler checks; for real runtime privacy there's #field.

  14. 14. What does the satisfies operator do?

    const palette = {
      red: [255, 0, 0],
      green: '#00ff00',
    } satisfies Record<string, string | number[]>;

    Correct answer: Checks conformance to the type but keeps the more precise inferred type

    With the annotation : Record<...>, palette.green would become string | number[]. With satisfies, the shape is checked, but palette.green stays string, so you can call .toUpperCase(). Unlike as, nothing is asserted without a check.

  15. 15. What are template literal types?

    type Event = 'click' | 'focus';
    type Handler = `on${Capitalize<Event>}`;

    Correct answer: String types built from other types by a template

    Template literals work at the type level and distribute over unions. There are built-in transformations: Uppercase, Lowercase, Capitalize, Uncapitalize. They're used to type event keys, CSS variables and routes.

  16. 16. Why is an as const object often used instead of an enum?

    const Status = { Active: 'active', Banned: 'banned' } as const;
    type Status = typeof Status[keyof typeof Status];

    Correct answer: It's a plain JS object, and the value type is a union of strings

    The object is standard JS: it can be iterated and is compatible with erasable syntax mode (Node.js type stripping). The type is a string union that also accepts literals from an API. Numeric enums, by contrast, accept any number and create a reverse mapping. Enums weren't removed.

  17. 17. How does const enum differ from a regular enum?

    Correct answer: Values are inlined at compile time; there's no object at runtime

    const enum saves bundle size but doesn't play well with isolatedModules and transpilers that process files individually (Babel, esbuild, SWC): they'd need to know values from another file. That's why libraries and modern builds avoid it.

  18. 18. How do namespaces (namespace) differ from ES modules?

    Correct answer: Namespaces are a legacy way of organizing code; modules are used now

    Namespaces predate ES modules and create objects at runtime. Code is now organized into files with import/export, while declare namespace is sometimes used in declarations to describe global libraries. Namespaces aren't compatible with erasableSyntaxOnly.

  19. 19. What is an assertion function?

    function assertIsString(x: unknown): asserts x is string {
      if (typeof x !== 'string') throw new Error('Not a string');
    }

    Correct answer: A function that narrows the type after a successful call

    After assertIsString(value), value is a string for the rest of the code, with no if. If the check fails, the function throws. Unlike a type guard (x is T), you don't need to wrap the result in a condition.

  20. 20. How do you get a typed e.detail in window.addEventListener('cart:add', (e) => ...) for your own event?

    Correct answer: Add the event to WindowEventMap via declare global

    addEventListener looks up the event type by name in WindowEventMap (and DocumentEventMap, HTMLElementEventMap). Declaration merging adds your entry: interface WindowEventMap { 'cart:add': CustomEvent<{ id: string }> } inside declare global. Then e.detail.id is a string in every listener. Nothing is inferred from dispatchEvent calls.

  21. 21. Why should groupBy return Partial<Record<K, T[]>> rather than Record<K, T[]>?

    function groupBy<T, K extends PropertyKey>(items: T[], getKey: (item: T) => K) { /* ... */ }
    const byStatus = groupBy(tasks, (t) => t.status); // K = 'todo' | 'done'

    Correct answer: Not every key of K is guaranteed to appear in the result

    If there are no done tasks, byStatus.done is undefined, yet Record<K, T[]> claims an array is always there, and byStatus.done.length crashes. Partial makes the values T[] | undefined and forces a check. The built-in Object.groupBy is typed exactly this way.

  22. 22. How do you type a timer id so the code compiles both in the browser and in Node.js?

    let timer: ???;
    timer = setTimeout(save, 500);
    clearTimeout(timer);

    Correct answer: ReturnType<typeof setTimeout>

    In the browser setTimeout returns a number, in Node.js a Timeout object, and when both dom and @types/node are loaded, the Node signature often wins. ReturnType<typeof setTimeout> takes whatever the current environment declares, so clearTimeout(timer) type-checks everywhere.

  23. 23. What does Extract<'a' | 'b' | 1 | 2, string> produce?

    Correct answer: 'a' | 'b'

    Extract<T, U> keeps the union members assignable to U - here, the string literals. The opposite Exclude would keep 1 | 2. Both utilities are distributive conditional types.

  24. 24. What does NonNullable<string | null | undefined> return?

    Correct answer: string

    NonNullable<T> excludes null and undefined from a union. It's currently implemented as T & {}. Handy for values after a check or in filter results.

  25. 25. How do object, {} and Record<string, unknown> differ as types?

    Correct answer: {} non-null, object non-primitive, Record a dictionary

    {} accepts strings and numbers too - everything except null and undefined, which often surprises people. object excludes primitives. Record<string, unknown> is an object with arbitrary string keys whose values you can access. For "any value", unknown is better.

  26. 26. How does TypeScript handle the in operator when narrowing?

    type Fish = { swim(): void };
    type Bird = { fly(): void };
    function move(a: Fish | Bird) {
      if ('swim' in a) a.swim(); else a.fly();
    }

    Correct answer: It narrows the union to the members that have a swim property

    TS supports narrowing via typeof, instanceof, in, equality checks, truthiness and discriminants. In else, Bird remains. For network data, such checks are part of runtime validation.

  27. 27. What do -readonly and -? do in a mapped type?

    type Mutable<T> = { -readonly [K in keyof T]-?: T[K] };

    Correct answer: Remove the readonly and ? modifiers from all properties

    The - prefix removes a modifier, + (the default) adds it. That's how Required<T> is implemented (-?). There's no built-in Mutable, but it's often written following this pattern.

  28. 28. How do you rename keys in a mapped type?

    type Getters<T> = {
      [K in keyof T as `get${Capitalize<string & K>}`]: () => T[K];
    };

    Correct answer: With as after in, using a template literal

    Key remapping (TS 4.1+): Getters<{ name: string }> → { getName: () => string }. If the expression after as produces never, the key is dropped - that's how properties are filtered by value type. string & K is needed because keys can be symbols or numbers.

  29. 29. Why does Object.keys(user) return string[] rather than (keyof User)[]?

    Correct answer: At runtime the object may have other keys too

    An object of type User may contain extra properties (the type describes a minimum), so promising (keyof User)[] would be unsafe. If you're sure, use a type assertion or a typed wrapper. It's a deliberate decision by the TypeScript team.

  30. 30. What does the noUncheckedIndexedAccess flag give you?

    Correct answer: Index access gets a type with | undefined

    Without the flag, const x = arr[10] is typed as T, even though it's undefined at runtime. With the flag, the compiler makes you check the value. The flag isn't part of strict, but it's often recommended.

  31. 31. How does unknown[] differ from any[] in a function parameter?

    Correct answer: With unknown[] elements must be narrowed, with any[] they don't

    Both accept any array, but inside a function with unknown you can't call an element's method without a check. If the function doesn't work with the elements (e.g. counts the length), unknown[] is the safe choice. Even better is a generic T[] if the type matters for the result.

  32. 32. What are decorators in TypeScript 5?

    Correct answer: Functions applied to classes and their members via @

    TS 5.0 supports standard (stage 3) decorators without a flag. The legacy "experimental" decorators (experimentalDecorators) with a different API are used in Angular, NestJS and TypeORM. Uses: logging, DI, validation, metadata.

  33. 33. What does import type { User } from './types' do?

    Correct answer: Imports only the type; the import is erased during compilation

    An explicit type-only import helps transpilers that process files individually: they know for sure the import can be erased. With the verbatimModuleSyntax flag, this is mandatory for types. It also avoids unwanted side effects from loading the module.

  34. 34. Why is interface preferable to an intersection for extending large object types?

    Correct answer: extends catches property conflicts and is faster for the compiler

    With interface B extends A, a property conflict is an error at the declaration, while an intersection silently produces never. The compiler caches interface relationships, so it's faster in large codebases - as the TS performance wiki recommends.

  35. 35. What does Parameters<(a: string, b?: number) => void> return?

    Correct answer: [a: string, b?: number]

    Parameters returns a tuple of parameters, preserving optionality and names. Handy for wrappers: function logged(...args: Parameters<typeof fn>). For constructors there's ConstructorParameters.

  36. 36. How do you specify the type of this for a handler function?

    function handler(this: HTMLButtonElement, e: MouseEvent) {
      this.disabled = true;
    }

    Correct answer: A leading this "parameter" sets the context type and is erased on compile

    The this pseudo-parameter describes which context the function must be called with; it isn't an argument. The compiler checks calls and uses of this inside. In arrow functions, this is lexical and can't be specified this way.

  37. 37. What's the best way to type an API response whose structure differs by status?

    Correct answer: A union discriminated by ok: success with data or an error

    A union makes impossible states unrepresentable: with ok: true, data is guaranteed and error isn't available. A type with optional fields allows meaningless combinations and requires checks everywhere.

  38. 38. What does the ReadonlyArray<T> utility (or readonly T[]) do?

    Correct answer: Removes mutating methods (push, sort) from the type

    A readonly T[] parameter guarantees the caller that the function won't modify their array. It accepts regular arrays too. The type doesn't prevent changing nested objects - it's shallow protection.

  39. 39. What is unique symbol?

    Correct answer: The type of a specific symbol declared via const s = Symbol()

    Each const with Symbol() gets its own unique symbol subtype, so TS distinguishes such keys. This is used for "hidden" properties and type branding. A plain symbol describes any symbol.

  40. 40. How do you extend the type of the global Window object from a module?

    export {};
    declare global {
      interface Window { dataLayer: unknown[] }
    }

    Correct answer: With declare global and merging into the Window interface

    In a module file (with import/export), global declarations go inside declare global. The Window interface merges with your extension. Redeclaring type Window causes a duplicate identifier error.

  41. 41. How do you type the result of JSON.parse safely?

    Correct answer: Treat the result as unknown and validate it with a schema (Zod)

    JSON.parse returns any, but external data may not match expectations. A schema (z.object({...})) validates data at runtime, and z.infer<typeof schema> gives a TS type without duplication. as User only hides the problem.

  42. 42. How does type A = B differ from interface A extends B {} in IDE tooltips?

    Correct answer: The interface is shown by name, the alias gets expanded

    Complex intersections and mapped types are often expanded into long structures in tooltips, while an interface is shown by name. This affects the readability of errors. To "flatten" intersections, people write a Prettify<T> helper.

  43. 43. What does paths in tsconfig.json give you?

    Correct answer: Import path aliases, e.g. @/* → ./src/*

    paths lets you write import { Button } from '@/components/button' instead of long relative paths. It's a resolution setting for the compiler - the bundler must understand the same aliases (Next.js and Vite read them from tsconfig). The file list is set by include, output by outDir.

  44. 44. How does moduleResolution: 'bundler' differ from 'node16'/'nodenext'?

    Correct answer: bundler mimics bundlers, nodenext follows Node.js

    In Node.js ESM you must write extensions in relative imports and account for exports/type. Bundlers (Vite, Next.js, esbuild) are forgiving about this, and bundler mode mirrors their behavior. For code run by Node.js without a build step, choose nodenext.

  45. 45. What does the isolatedModules flag do?

    Correct answer: Forbids code that can't be transpiled file by file

    Babel, SWC and esbuild compile files independently and don't see types from other modules. isolatedModules warns about code they can't handle correctly: re-exporting a type without export type, accessing a const enum from another file, and so on.

  46. 46. What does keyof typeof obj do?

    const routes = { home: '/', about: '/about' };
    type RouteName = keyof typeof routes;

    Correct answer: Gets the union of the routes value's keys: 'home' | 'about'

    typeof routes gives the object's type, and keyof its keys. For a union of values you need indexed access: typeof routes[keyof typeof routes], and as const to make the values literals.

  47. 47. When does TS widen a literal type to a general one?

    Correct answer: In mutable positions: let, object properties

    const a = 'x' → 'x', but let b = 'x' → string, and { dir: 'left' } → { dir: string }. Because of this, the object can't be passed to a function expecting 'left' | 'right'. Fixes: as const, an annotation or satisfies.

  48. 48. How do you make a generic parameter optional with a default value?

    Correct answer: type Box<T = string> = { value: T }

    Type parameters can have defaults: Box without an argument is Box<string>. They can be combined with constraints: <T extends object = {}>. That's how, for example, useState<S = undefined> and EventEmitter<T = any> work.

  49. 49. How do you type a factory function that returns the same type it received?

    Correct answer: function clone<T>(value: T): T

    A generic preserves the link between input and output: clone(user) returns a User. With any and object, the calling code loses type information and has to cast.

  50. 50. What is contextual typing?

    Correct answer: Inferring a function's parameter types from where it's used

    In button.addEventListener('click', e => ...), the type of e (MouseEvent) is inferred from the addEventListener signature. map callbacks, JSX handlers and useState setters work the same way. If you move the function into a separate variable, the context is lost - you'll have to annotate it.

  51. 51. Why does Omit<Circle | Square, 'id'> lose the discriminated union?

    type DistributiveOmit<T, K extends PropertyKey> = T extends any ? Omit<T, K> : never;

    Correct answer: Omit sees only common keys; it isn't distributive

    keyof (A | B) contains only shared keys, so member-specific properties disappear. The conditional type distributes over the union.

  52. 52. What does as const satisfies Record<string, Route> give you for a config object?

    const routes = {
      home: { path: '/' },
      user: { path: '/users/:id' },
    } as const satisfies Record<string, { path: string }>;

    Correct answer: Shape validation with exact literals preserved

    keyof typeof routes stays 'home' | 'user', and a typo in a property is still reported.

  53. 53. When should you prefer a union parameter over overloads?

    function len(x: string | any[]): number { return x.length; }

    Correct answer: When the return type doesn't depend on the input

    Overloads can't be called with a value of the union type unless an overload accepts the union. Use them only when inputs map to different outputs.

  54. 54. What are parameter properties, and why are they not "erasable" syntax?

    class User {
      constructor(private readonly name: string) {}
    }

    Correct answer: Constructor parameters that become fields; TS must emit that code

    Since they emit JavaScript, they're rejected by erasableSyntaxOnly and by runtimes that only strip types.

  55. 55. What do the override keyword and noImplicitOverride protect against?

    Correct answer: Accidental overrides and overrides left after a base rename

    With the flag, every overriding member must say override, and override on a member that doesn't exist in the base class is an error.

  56. 56. Why might Readonly<Settings> not prevent this change?

    const s: Readonly<Settings> = load();
    s.theme.colors.primary = 'red';

    Correct answer: Readonly is shallow; nested objects stay mutable

    A recursive DeepReadonly type or as const for literals protect nested levels at the type level.

  57. 57. How do you derive a TypeScript type from a Zod schema?

    const User = z.object({ id: z.string(), age: z.number() });
    type User = z.infer<typeof User>;

    Correct answer: With z.infer<typeof Schema>, one source of truth

    Validation at the boundary (API, forms) plus inferred types avoids drift between runtime checks and compile-time types.

  58. 58. What does type-aware linting with typescript-eslint add on top of tsc?

    Correct answer: Rules using type info, e.g. floating promises

    tsc checks type correctness; lint rules like no-floating-promises catch bugs that are type-correct but likely wrong.

  59. 59. How do you share one strict base configuration between many packages?

    { "extends": "@tsconfig/strictest/tsconfig.json", "include": ["src"] }

    Correct answer: extends in each tsconfig.json, to a shared base

    Community bases (@tsconfig/node22, @tsconfig/strictest, ...) or an internal package keep settings consistent.

  60. 60. How do target and lib differ in tsconfig.json?

    Correct answer: target: emitted JS syntax; lib: declared built-in APIs

    lib doesn't add polyfills: declaring ES2023 lets you call findLast, but old browsers still need a polyfill.

  61. 61. What does esModuleInterop fix?

    import express from 'express'; // a CommonJS module

    Correct answer: Default-importing CommonJS modules the way bundlers do

    Without it you'd need import * as express from 'express', which breaks when the module is callable.

  62. 62. Which option lets you import config from './config.json' with typed contents?

    Correct answer: resolveJsonModule

    TypeScript infers the type from the JSON file content. Values are widened (e.g. strings, not literals).

  63. 63. How do you get the instance type and constructor arguments of a class?

    type Svc = InstanceType<typeof ApiService>;
    type Args = ConstructorParameters<typeof ApiService>;

    Correct answer: InstanceType and ConstructorParameters on typeof Class

    ApiService as a type already means the instance type; typeof ApiService is the constructor itself.

  64. 64. How do you narrow the results of Promise.allSettled?

    const results = await Promise.allSettled(tasks);
    const values = results.filter((r) => r.status === 'fulfilled').map((r) => r.value);

    Correct answer: Check status; TS 5.5 infers the filter as a predicate

    PromiseSettledResult<T> is a discriminated union of fulfilled (value) and rejected (reason) results.

  65. 65. What do the intrinsic types Uppercase, Capitalize etc. allow?

    type Getter<K extends string> = `get${Capitalize<K>}`;
    type G = Getter<'name'>; // 'getName'

    Correct answer: Transforming string literal types at compile time

    They let you derive names like getName/onClick from keys, keeping APIs consistent automatically.

  66. 66. What do noImplicitReturns and noFallthroughCasesInSwitch catch?

    Correct answer: Missed returns and accidental case fall-through

    They're not part of strict but catch common logic bugs cheaply.

  67. 67. How do you type a generator function?

    function* ids(): Generator<number, void, unknown> {
      let i = 0;
      while (true) yield i++;
    }

    Correct answer: Generator<Yield, Return, Next>

    The third parameter is the type of values passed to next(...). Async generators use AsyncGenerator<...>.

  68. 68. What is the type of err in promise.catch((err) => ...) with strict enabled?

    Correct answer: any - the flag covers only try/catch blocks

    useUnknownInCatchVariables changes only catch (e) clauses. In the Promise types, onrejected receives reason: any, so err.message compiles even if a string was rejected. Annotate it yourself, (err: unknown) => ..., or use try/catch with await.

  69. 69. When is Map<K, V> a better choice than an index signature object?

    Correct answer: Non-string keys, frequent changes, prototype-name collisions

    map.get(key) is typed as V | undefined, which also forces handling missing keys.

  70. 70. What do the types/typesVersions and the exports "types" condition in package.json do?

    Correct answer: Tell TypeScript where a package's declarations live

    With exports, put the types condition first in each entry, otherwise TypeScript may resolve the JS file and find no types.

  71. 71. What does export type * from './types' do (TS 5.0+)?

    Correct answer: Re-exports all types for use in type positions only

    It's fully erased at compile time and pairs well with verbatimModuleSyntax and type-only barrels.

  72. 72. How do you write a type for any JSON value?

    type Json = string | number | boolean | null | Json[] | { [key: string]: Json };

    Correct answer: A recursive union referencing itself

    Recursive type aliases are allowed when the recursion goes through object or array types.

  73. 73. How do you implement a type-safe event emitter?

    type Events = { login: { userId: string }; logout: undefined };
    on<K extends keyof Events>(event: K, cb: (payload: Events[K]) => void): void;

    Correct answer: An event map plus a generic key, so payloads follow names

    A typo in an event name or a wrong payload becomes a compile error.

  74. 74. Does narrowing work when a discriminated union is destructured first?

    const { kind, radius } = shape;
    if (kind === 'circle') radius.toFixed();

    Correct answer: Yes, since TS 4.6, for const destructuring

    The destructured variables must be const (or unmodified parameters) for control-flow analysis to connect them.

  75. 75. What does switch (true) narrowing (TS 5.3) enable?

    switch (true) {
      case typeof x === 'string': return x.toUpperCase();
      case Array.isArray(x): return x.length;
    }

    Correct answer: Each case condition narrows the value in its branch

    It's a readable alternative to long if/else if chains with type guards.