TypeScript Senior 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. With strictFunctionTypes, can you assign (x: Dog) => void to a variable of type (x: Animal) => void?

    Correct answer: No: function parameters are checked contravariantly

    The variable promises to accept any Animal, but the function can only handle Dog - a call with Cat would break. So subtyping by parameter goes the opposite way: (x: Animal) => void can be assigned where (x: Dog) => void is expected, but not vice versa.

  2. 2. Why doesn't strictFunctionTypes apply to a method declared as handle(x: Dog): void?

    Correct answer: Method-syntax parameters are checked bivariantly for compatibility

    Method bivariance was kept so that many built-in types (e.g. Array<T>) stay compatible. If you declare a function property handle: (x: Dog) => void instead, the check is strict. That's why property syntax is often preferred for callbacks in interfaces.

  3. 3. What is ToArray<string | number> if type ToArray<T> = T extends any ? T[] : never?

    Correct answer: string[] | number[]

    A conditional type over a "naked" type parameter distributes over a union: the condition is applied to each member separately. This is a distributive conditional type - Exclude and Extract are built on it.

  4. 4. How do you turn off a conditional type's distribution over a union?

    Correct answer: Wrap both sides in a tuple: [T] extends [U] ? X : Y

    Distribution happens only when the checked type is a "naked" parameter. The tuple [T] makes it composite, so the union is checked as a whole: [string | number] extends [string] → false. There's no compiler setting for this.

  5. 5. Why does type IsNever<T> = T extends never ? true : false give never for IsNever<never>?

    Correct answer: never is an empty union, and distributing over it yields an empty result

    A distributive conditional type applies to each union member, and never has no members - the result is never. The correct check is [T] extends [never] ? true : false.

  6. 6. How do you implement DeepPartial<T>?

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

    Correct answer: With a recursive mapped type that adds ? at every level

    Type aliases can reference themselves. A real implementation should handle arrays, functions and Date separately so they aren't "broken down" into properties. Deep recursion has an instantiation limit, so huge types slow down the compiler.

  7. 7. Why are branded types needed?

    type UserId = string & { readonly __brand: 'UserId' };

    Correct answer: To tell apart identical shapes, e.g. UserId and OrderId

    Structural typing considers all strings compatible, so deleteUser(orderId) compiles. A brand is a fake property that exists only in types; the value is created by a constructor function with a check (toUserId(s): UserId). This emulates nominal typing.

  8. 8. How do you keep only the function-valued properties of a type?

    type Methods<T> = {
      [K in keyof T as T[K] extends Function ? K : never]: T[K];
    };

    Correct answer: Remapping a key to never drops the property from the result

    If the expression after as evaluates to never, the key is dropped. It's the standard technique for filtering keys by value type. Without as, you'd first compute the union of keys and then apply Pick.

  9. 9. What does Split<'a/b/c'> return?

    type Split<S extends string> =
      S extends `${infer Head}/${infer Rest}`
        ? [Head, ...Split<Rest>]
        : [S];

    Correct answer: ['a', 'b', 'c']

    infer inside a template literal parses the string: Head captures the part before the first /, Rest the remainder. Recursion and variadic tuples assemble the result. This is how route params like /users/:id are typed.

  10. 10. What are variadic tuple types?

    type Concat<A extends unknown[], B extends unknown[]> = [...A, ...B];

    Correct answer: Tuples where spreading generic tuples preserves exact element types

    Concat<[1, 2], ['a']> → [1, 2, 'a']. This lets you precisely type concat, curry, Promise.all and wrapper functions with prefix arguments.

  11. 11. What does the const modifier on a type parameter (TS 5.0) give you?

    function routes<const T extends readonly string[]>(r: T) { return r; }
    const r = routes(['home', 'about']);

    Correct answer: Literal inference, like as const: r is readonly ['home', 'about']

    Without const, string[] would be inferred, and the caller would have to write as const. The modifier affects only type inference, not runtime. The readonly string[] constraint is needed so an array literal fits as a readonly tuple.

  12. 12. What is the NoInfer<T> utility (TS 5.4) for?

    function pick<C extends string>(colors: C[], fallback: NoInfer<C>) {}
    pick(['red', 'blue'], 'green');

    Correct answer: It prevents inferring C from this argument - so there's an error

    Without NoInfer, TS would infer C as 'red' | 'blue' | 'green' from both arguments, and there'd be no error. NoInfer says: "take C from elsewhere and only check this argument".

  13. 13. What does infer N extends number do in a conditional type?

    type ToNum<S> = S extends `${infer N extends number}` ? N : never;
    type X = ToNum<'42'>;

    Correct answer: Infers N with a constraint - X becomes the literal type 42

    A constraint on infer (TS 4.7+) not only checks compatibility but also lets you infer a literal numeric type from a string. Previously this required nested conditional types.

  14. 14. In what order should function overloads be written?

    Correct answer: From more specific to more general - TS picks the first match from the top

    If a general overload (x: any) comes first, it "captures" every call and the specific signatures become useless. Another tip: don't write overloads that differ only in the last parameter - use an optional parameter instead.

  15. 15. How do you add a user field to the Express library's Request type?

    declare module 'express-serve-static-core' {
      interface Request { user?: User }
    }

    Correct answer: Module augmentation via declare module and merging

    Augmentation lets you extend a third-party module's types without forking it: the interfaces merge. The file must be a module (contain import/export) and be part of the project. Edits in node_modules are lost on reinstall.

  16. 16. What does the verbatimModuleSyntax flag require?

    Correct answer: Explicitly marking type imports with import type

    The rule is simple: everything without the type modifier stays in the output JS, everything with type is erased. This makes the result predictable for any transpiler and replaces the deprecated importsNotUsedAsValues and preserveValueImports.

  17. 17. What does the erasableSyntaxOnly flag (TS 5.8) forbid?

    Correct answer: Syntax that requires code generation: enum, namespace

    Node.js can run TypeScript by simply erasing types (type stripping). Constructs that require code generation don't work that way. The flag reports them in advance so the code runs without a separate compile step.

  18. 18. What are Project References (references, composite) for?

    Correct answer: Splitting a repository into incrementally built projects

    Each subproject compiles separately and emits .d.ts, and dependent projects use the declarations rather than the sources. This speeds up type checking and enforces boundaries between monorepo packages.

  19. 19. What's the risk of enabling skipLibCheck: true?

    Correct answer: Errors inside .d.ts files, including your own, go unnoticed

    The flag skips checking declaration files - builds are faster and don't break because of conflicts between @types. But errors in declarations (including your own .d.ts) remain unnoticed. It doesn't prevent using library types.

  20. 20. How do you find the cause of slow type checking in a large project?

    Correct answer: tsc --extendedDiagnostics and --generateTrace

    Diagnostics show the time of each phase and the number of instantiations, and a trace (analyzed with @typescript/analyze-trace or in the browser) shows which types are the most expensive. Common culprits: huge unions, deep recursion, complex intersections, missing return type annotations on exports.

  21. 21. Can you pass a readonly string[] to a function that accepts string[]?

    Correct answer: No: the function could modify the array

    The reverse direction (string[] → readonly string[]) is allowed. So parameters that the function doesn't modify are better declared as readonly T[] - then it can be called with both mutable and readonly arrays.

  22. 22. What does a this return type give you in a class method?

    class Query {
      where(c: string): this { /* ... */ return this; }
    }
    class UserQuery extends Query { active(): this { return this; } }
    new UserQuery().where('x').active();

    Correct answer: Polymorphic this: a method chain keeps the subclass type

    If where returned Query, .active() wouldn't be available after it. Polymorphic this is handy for fluent APIs and builders. There's also this is T in type guard methods.

  23. 23. What are the in and out variance annotations on type parameters (TS 4.7) for?

    interface Producer<out T> { get(): T }
    interface Consumer<in T> { set(v: T): void }

    Correct answer: They state variance explicitly, speeding up checks

    TS usually computes variance itself, but for complex recursive types this is expensive and sometimes imprecise. The annotation is checked by the compiler and used in comparisons. It's rarely needed - in libraries with complex types.

  24. 24. Why can the template type ` ${A}-${B}-${C} ` over three large unions cause an error?

    Correct answer: The resulting union is too large, and the compiler has a limit

    A template with unions distributes over every combination: 100 × 100 × 100 = 1,000,000 members. TypeScript limits union size (around 100,000) and reports "Expression produces a union type that is too complex". The fix is a more general type (` ${string}-${string} `) or validation via a function.

  25. 25. How does the UnionToIntersection trick work?

    type UnionToIntersection<U> =
      (U extends any ? (x: U) => void : never) extends (x: infer I) => void
        ? I : never;

    Correct answer: Inference from a contravariant position gives an intersection

    First the union is distributed into a union of functions (x: A) => void | (x: B) => void. Then, when inferring I from the (contravariant) parameter position, multiple candidates are combined into an intersection: A & B. It's a textbook example of type-level programming.

  26. 26. Why is Record<Status, string> more useful than { [k: string]: string } for a dictionary keyed by status?

    Correct answer: The compiler requires a key for every status

    Add a new member to the Status union, and every Record<Status, ...> stops compiling until you add a translation, an icon and so on. An index signature accepts any string and doesn't guarantee completeness.

  27. 27. What changed about type predicate inference in TS 5.5?

    const nums = [1, null, 2].filter(x => x !== null);

    Correct answer: TS infers the predicate x is number, so nums is number[]

    Previously nums was (number | null)[], and you had to write (x): x is number => x !== null. Now the compiler infers a predicate for simple functions if returning true really narrows the type.

  28. 28. What are using declarations (TS 5.2) for?

    {
      using file = openFile('log.txt');
      // ...
    } // file[Symbol.dispose]() is called automatically

    Correct answer: Automatically calling Symbol.dispose when leaving the block

    It implements the ECMAScript Explicit Resource Management proposal: the resource is released even if an exception is thrown - like try/finally, but shorter. For async resources there's await using and Symbol.asyncDispose. Handy for connections, files, locks and subscriptions in tests.

  29. 29. What does (typeof users)[number] return if users: User[]?

    Correct answer: User

    Indexed access by number returns the array element type or a union of tuple element types. A popular combo: const roles = [...] as const; type Role = (typeof roles)[number].

  30. 30. What does the mapped type { [K in keyof T]: Box<T[K]> } produce if T is the tuple [string, number]?

    Correct answer: The tuple [Box<string>, Box<number>]

    A mapped type over keyof T, where T is a tuple or array type parameter, maps the elements and preserves tuple-ness, length and modifiers. This lets you type, for example, Promise.all via { [K in keyof T]: Awaited<T[K]> }.

  31. 31. How do you get the element type of a Set<T> or Map<K, V> from a value?

    const ids = new Set(['a', 'b']);
    type Id = typeof ids extends Set<infer T> ? T : never;

    Correct answer: With a conditional type using infer on the pattern Set<infer T>

    Set has no numeric index signature, so [number] doesn't work. A conditional type with infer extracts the parameter of any generic: Map<infer K, infer V>, Promise<infer R>. There's no built-in ElementType utility. Here Id is string.

  32. 32. What is the declare keyword for?

    declare const __APP_VERSION__: string;

    Correct answer: Describing what exists at runtime, emitting no code

    Ambient declarations tell the compiler about things defined elsewhere: globals injected by the bundler, scripts from a CDN, modules without types (declare module 'legacy-lib'). declare doesn't produce any JS code.

  33. 33. How do you check a type in tests so that you get an error if there's NO compile error?

    Correct answer: // @ts-expect-error above the line being checked

    @ts-expect-error suppresses an error and itself becomes an error if there's nothing to suppress - so a type test "fails" when a type becomes too wide. @ts-ignore is always silent and hides problems. For assertions there's expectTypeOf in Vitest, tsd, and @ts-expect-error in type-challenges.

  34. 34. When is the double assertion x as unknown as T justified?

    Correct answer: Almost never: only for a deliberate workaround backed by a check

    A plain as is forbidden between unrelated types; via unknown you can assert anything - and be wrong. If you can't avoid it (e.g. in a low-level utility), hide it inside a function with a runtime check and tests. For JSON, validate with a schema.

  35. 35. Why should you avoid the Function type for callbacks?

    Correct answer: It accepts any function, and calls aren't checked

    Function describes any function, and calling it is unsafe. Prefer a precise signature (value: string) => void, and for "any function" use (...args: never[]) => unknown or (...args: any[]) => any. Likewise, Object and {} are better replaced with object or unknown.

  36. 36. Why can't you write a.x for a: { x: string } | { y: number }?

    Correct answer: Only common properties are accessible; narrow with in

    The compiler doesn't know which member a is, and the second has no x. After if ('x' in a) the type is narrowed. Alternatives are a common discriminant (kind) or an explicit x?: undefined in the second member.

  37. 37. What does the exactOptionalPropertyTypes flag change?

    Correct answer: { a?: string } rejects an explicit a: undefined

    Without the flag, a?: string is equivalent to a?: string | undefined. With it, "no key" and "key present with value undefined" are distinguished, which matters for Object.keys, in and spread. If undefined is needed explicitly, write a?: string | undefined.

  38. 38. What does keyof (A | B) return if A = { id; name } and B = { id; price }?

    Correct answer: 'id'

    A union value can be any of its members, so only common keys are safe to access. keyof (A & B) gives the union of all keys. To distribute keyof over union members, use a conditional type: T extends any ? keyof T : never.

  39. 39. How do you enable type checking in JS files without migrating to TS?

    Correct answer: // @ts-check and types via JSDoc

    TypeScript understands JSDoc: /** @param {string} name */, @type, @typedef, and type imports via @import. Many JS libraries are typed this way, and it enables gradual migration. Checking works in the editor and via tsc --noEmit.

  40. 40. How do you type a parameter that accepts an abstract class constructor?

    Correct answer: abstract new (...args: any[]) => T

    Abstract construct signatures (TS 4.2) let you accept both abstract and regular classes - e.g. in mixin functions. new (...args) => T won't accept an abstract class. There's no built-in Constructor<T>; people usually declare it themselves.

  41. 41. Is the narrowing of a let variable preserved inside a callback?

    function f(x: string | number) {
      if (typeof x === 'string') {
        setTimeout(() => x.toUpperCase());
      }
    }

    Correct answer: Yes, since TS 5.4, if the variable isn't reassigned afterwards

    Previously, inside a callback TS assumed x might be reassigned and reset the narrowing to string | number. Since 5.4, the compiler understands the value is stable after the last assignment and keeps the narrowing. For const it already worked before.

  42. 42. What is a homomorphic mapped type, and what does it preserve?

    Correct answer: A { [K in keyof T]: ... } type that preserves T's modifiers

    When a mapped type iterates over keyof T directly, TS carries over the property modifiers of T. That's why Partial<Readonly<T>> stays readonly. When iterating over an arbitrary union of keys (K in 'a' | 'b'), modifiers aren't preserved.

  43. 43. How do you type a Promise.all-like function over a tuple of promises?

    Correct answer: A generic tuple [...T] and a mapped type with Awaited<T[K]>

    [...T] hints to infer a tuple rather than an array, and the homomorphic mapped type unwraps each element: all([fetchUser(), fetchPosts()]) → Promise<[User, Post[]]>. Versions with any or a single T lose positional types.

  44. 44. Why is it recommended to annotate return types of exported functions in a library?

    Correct answer: It speeds up checking and pins down the public contract

    Inferring a complex type has to be repeated wherever the function is used, and declarations get bulky. An explicit type keeps the contract stable: implementation changes don't "leak" into the API. With isolatedDeclarations (TS 5.5), annotations on exports become mandatory.

  45. 45. Why is isolatedDeclarations (TS 5.5) useful for monorepos?

    Correct answer: It allows generating .d.ts per file and in parallel

    The flag requires exported APIs to be explicitly annotated - then declarations can be produced by looking at a single file. This lets third-party tools (oxc, swc) generate .d.ts in parallel without waiting for a full check of dependencies.

  46. 46. How does T extends object differ from T extends {} as a generic constraint?

    Correct answer: object - non-primitives, {} - everything except null/undefined

    {} means "any value with properties", and strings and numbers have properties, so T extends {} accepts 'abc' and 42. To allow only objects (including arrays and functions), use object. For "anything except null/undefined", {} is exactly what you need.

  47. 47. Why is extending an interface faster for the compiler than an intersection?

    Correct answer: Interface relationships are cached, while intersections are recomputed

    The compiler caches the result of comparing interfaces by name, while an intersection A & B & C has to be normalized and compared structurally every time. In hot paths with large types this is noticeable. The TypeScript performance wiki says so explicitly.

  48. 48. How do you type a reducer so that payload depends on the action's type?

    Correct answer: Describe the actions as a union discriminated by the type field

    type Action = { type: 'add'; payload: Todo } | { type: 'remove'; payload: { id: string } } - in case 'add' TS knows payload is a Todo. With never in default you get an exhaustiveness check. Redux Toolkit generates such types automatically from createSlice.

  49. 49. What does T[keyof T] return for T = { a: string; b: number }?

    Correct answer: string | number

    Indexed access by a union of keys gives a union of value types. It's often used to get the union of a constant object's values: typeof obj[keyof typeof obj].

  50. 50. What is declare module '*.svg' used for?

    declare module '*.svg' {
      const src: string;
      export default src;
    }

    Correct answer: To describe the import type of assets handled by the bundler

    Wildcard module declarations describe what importing bundler-handled files returns (images, CSS Modules, ?raw). Frameworks usually ship such declarations themselves (next-env.d.ts, vite/client).

  51. 51. Why does this compile, and what's the soundness hole?

    const dogs: Dog[] = [];
    const animals: Animal[] = dogs;
    animals.push(new Cat());

    Correct answer: Covariant arrays: a wider alias can write a Cat into Dog[]

    Accepting readonly Animal[] in APIs that only read avoids the problem, since nothing can be written through it.

  52. 52. What does tail-recursion elimination for conditional types (TS 4.5) allow?

    Correct answer: Tail-position recursion goes much deeper, about 1000 levels

    Write recursive types with an accumulator so the recursive call is the whole branch result, e.g. Trim<Rest, [...Acc, X]>.

  53. 53. How do you extract route params from a path string type?

    type Params<P> = P extends `${string}:${infer K}/${infer R}`
      ? K | Params<R>
      : P extends `${string}:${infer K}` ? K : never;
    type T = Params<'/users/:id/posts/:postId'>; // 'id' | 'postId'

    Correct answer: Recursive template literal types with infer

    Routers like TanStack Router and typed Express helpers use this to make params.id type-safe.

  54. 54. How does a type-safe builder accumulate information in its type?

    class Query<T extends object = {}> {
      where<K extends string, V>(k: K, v: V): Query<T & Record<K, V>> { /* ... */ }
    }

    Correct answer: Each method returns a builder with a wider type parameter

    The final .build() can then return a precise type, and invalid call orders can be prevented.

  55. 55. TypeScript has no higher-kinded types. How do libraries emulate F<A> where F is generic?

    Correct answer: A registry interface mapping URIs to type constructors

    fp-ts and Effect use such encodings to write functions generic over containers like Option or Array.

  56. 56. What does the error "The inferred type of 'x' cannot be named without a reference to ..." mean?

    Correct answer: Declaration emit can't name the type; annotate or export it

    It shows up with declaration: true in libraries and monorepos. Explicit return types also make declaration emit faster.

  57. 57. Why does a dual ESM/CJS package need separate declaration files (e.g. .d.mts and .d.cts)?

    Correct answer: Each declaration file is read in one module format

    Mismatches cause "masquerading" types and broken default imports. Tools like "Are the types wrong?" detect them.

  58. 58. What does rewriteRelativeImportExtensions (TS 5.7) enable?

    import { util } from './util.ts'; // emitted as './util.js'

    Correct answer: .ts extensions in imports that work before and after compiling

    It pairs with Node's type stripping: the same source runs directly and also compiles to correct JS imports.

  59. 59. What is the main goal of TypeScript's native (Go) port?

    Correct answer: Much faster checks and editors, with the same type system

    The compiler is ported rather than redesigned, so type-checking results should match the JavaScript-based implementation.

  60. 60. What do the typescript-eslint no-unsafe-* rules help with?

    Correct answer: Containing any: they flag unsafe uses of any values

    any spreads silently through code. These rules force a conversion to unknown or a validated type at the boundary.

  61. 61. What does an assertion function require to work as a narrowing call?

    const assertUser: (x: unknown) => asserts x is User = (x) => { /* ... */ };

    Correct answer: The called function needs an explicit type annotation

    Otherwise TypeScript reports "Assertions require every name in the call target to be declared with an explicit type annotation".

  62. 62. What does a this is predicate do in a class method?

    class Node {
      isLeaf(): this is Leaf { return this.children.length === 0; }
    }

    Correct answer: It narrows the object when the method returns true

    Calling if (node.isLeaf()) narrows node inside the branch, like a regular type guard.

  63. 63. What is { id: string } & { id: number }?

    Correct answer: A type where id is never, so no value fits

    Conflicting intersections don't fail immediately; errors appear later in confusing places. Prefer interface extends, which reports conflicts at once.

  64. 64. How do you get the type of a module's exports without importing its values?

    type Api = typeof import('./api');

    Correct answer: With a type-only typeof import('...')

    This is handy for lazy-loaded modules: you can type the result of a dynamic import() without bundling it eagerly.

  65. 65. Why do excess property checks miss errors in this case?

    const input = { name: 'A', nmae: 'typo' };
    const user: User = input; // no error

    Correct answer: The checks apply only to fresh object literals

    TypeScript has no exact object types. Assign literals directly, or use satisfies at the literal to keep the check.

  66. 66. Why can a large union of string literals slow down the compiler?

    Correct answer: Many operations scale with the number of members

    Prefer string with branded or validated types where unions grow into the thousands; check with --extendedDiagnostics.

  67. 67. Why can a let variable lose its narrowing inside a callback but a const keeps it?

    Correct answer: A let may be reassigned before the callback runs

    Recent versions preserve narrowing for let in closures created after the last assignment, but copying into a const is the simple fix.

  68. 68. Why should a public library avoid enum in its API?

    Correct answer: They're nominal and emit runtime code

    A union of string literals (with an as const object if you need runtime values) is erasable and friendlier to consumers.

  69. 69. How do you type a function that preserves the exact keys of an object passed to it while transforming values?

    function mapValues<T extends object, R>(obj: T, fn: (v: T[keyof T]) => R): { [K in keyof T]: R } { /* ... */ }

    Correct answer: A mapped type over keyof T in the return type

    Callers keep autocompletion and typo checks on keys. Note Object.entries inside still loses key types and needs a cast.

  70. 70. How do you prevent consumers from depending on internal types of your library?

    Correct answer: A deliberate API: exports plus stripped @internal types

    Every exported type becomes part of the semver contract; a smaller surface makes changes safer.

  71. 71. What problem can strictNullChecks: false in one package cause in a monorepo?

    Correct answer: Emitted types may omit null, giving false guarantees

    Consistent strictness across packages, via a shared base config, prevents type information from being lost at boundaries.

  72. 72. Why are explicit generic constraints better than casting inside a generic function?

    function byId<T extends { id: string }>(items: T[], id: string): T | undefined {
      return items.find((i) => i.id === id);
    }

    Correct answer: The compiler verifies access and keeps T precise

    Casting ((i as any).id) hides mistakes; the constraint documents and checks the requirement.

  73. 73. What does Object.freeze return in terms of types?

    const config = Object.freeze({ mode: 'dark', retries: 3 });

    Correct answer: A shallow Readonly<...> with literal primitives

    Nested objects are neither frozen at runtime nor readonly in the type. as const makes all levels readonly at the type level only.

  74. 74. How can you make a discriminated union exhaustive check also catch a missing case at the data layer?

    const labels = { draft: 'Draft', published: 'Live' } satisfies Record<Status, string>;

    Correct answer: satisfies Record<Union, ...> on lookup tables

    Lookup objects complement switch + never checks: both make new union members fail loudly at compile time.

  75. 75. Why is it risky to type an API client with generics alone, like get<T>(url): Promise<T>?

    Correct answer: The generic is an unchecked assertion: any T compiles

    Generate types from an OpenAPI schema or validate responses with a schema so the declared type matches reality.