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.
1. With
strictFunctionTypes, can you assign(x: Dog) => voidto 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 handleDog- a call withCatwould break. So subtyping by parameter goes the opposite way:(x: Animal) => voidcan be assigned where(x: Dog) => voidis expected, but not vice versa.2. Why doesn't
strictFunctionTypesapply to a method declared ashandle(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 propertyhandle: (x: Dog) => voidinstead, the check is strict. That's why property syntax is often preferred for callbacks in interfaces.3. What is
ToArray<string | number>iftype 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 -
ExcludeandExtractare built on it.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 : YDistribution 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. Why does
type IsNever<T> = T extends never ? true : falsegiveneverforIsNever<never>?Correct answer:
neveris an empty union, and distributing over it yields an empty resultA distributive conditional type applies to each union member, and
neverhas no members - the result isnever. The correct check is[T] extends [never] ? true : false.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 levelType aliases can reference themselves. A real implementation should handle arrays, functions and
Dateseparately so they aren't "broken down" into properties. Deep recursion has an instantiation limit, so huge types slow down the compiler.7. Why are branded types needed?
type UserId = string & { readonly __brand: 'UserId' };Correct answer: To tell apart identical shapes, e.g.
UserIdandOrderIdStructural 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. 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
neverdrops the property from the resultIf the expression after
asevaluates tonever, the key is dropped. It's the standard technique for filtering keys by value type. Withoutas, you'd first compute the union of keys and then applyPick.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']inferinside a template literal parses the string:Headcaptures the part before the first/,Restthe remainder. Recursion and variadic tuples assemble the result. This is how route params like/users/:idare typed.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 typeconcat,curry,Promise.alland wrapper functions with prefix arguments.11. What does the
constmodifier 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:risreadonly ['home', 'about']Without
const,string[]would be inferred, and the caller would have to writeas const. The modifier affects only type inference, not runtime. Thereadonly string[]constraint is needed so an array literal fits as a readonly tuple.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
Cfrom this argument - so there's an errorWithout
NoInfer, TS would inferCas'red' | 'blue' | 'green'from both arguments, and there'd be no error.NoInfersays: "takeCfrom elsewhere and only check this argument".13. What does
infer N extends numberdo in a conditional type?type ToNum<S> = S extends `${infer N extends number}` ? N : never; type X = ToNum<'42'>;Correct answer: Infers
Nwith a constraint -Xbecomes the literal type42A 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. 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. How do you add a
userfield to the Express library'sRequesttype?declare module 'express-serve-static-core' { interface Request { user?: User } }Correct answer: Module augmentation via
declare moduleand mergingAugmentation 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 innode_modulesare lost on reinstall.16. What does the
verbatimModuleSyntaxflag require?Correct answer: Explicitly marking type imports with
import typeThe rule is simple: everything without the
typemodifier stays in the output JS, everything withtypeis erased. This makes the result predictable for any transpiler and replaces the deprecatedimportsNotUsedAsValuesandpreserveValueImports.17. What does the
erasableSyntaxOnlyflag (TS 5.8) forbid?Correct answer: Syntax that requires code generation:
enum,namespaceNode.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. 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. What's the risk of enabling
skipLibCheck: true?Correct answer: Errors inside
.d.tsfiles, including your own, go unnoticedThe 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. How do you find the cause of slow type checking in a large project?
Correct answer:
tsc --extendedDiagnosticsand--generateTraceDiagnostics show the time of each phase and the number of instantiations, and a trace (analyzed with
@typescript/analyze-traceor 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. Can you pass a
readonly string[]to a function that acceptsstring[]?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 asreadonly T[]- then it can be called with both mutable and readonly arrays.22. What does a
thisreturn 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 typeIf
wherereturnedQuery,.active()wouldn't be available after it. Polymorphicthisis handy for fluent APIs and builders. There's alsothis is Tin type guard methods.23. What are the
inandoutvariance 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. 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. How does the
UnionToIntersectiontrick 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 inferringIfrom the (contravariant) parameter position, multiple candidates are combined into an intersection:A & B. It's a textbook example of type-level programming.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
Statusunion, and everyRecord<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. 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, sonumsisnumber[]Previously
numswas(number | null)[], and you had to write(x): x is number => x !== null. Now the compiler infers a predicate for simple functions if returningtruereally narrows the type.28. What are
usingdeclarations (TS 5.2) for?{ using file = openFile('log.txt'); // ... } // file[Symbol.dispose]() is called automaticallyCorrect answer: Automatically calling
Symbol.disposewhen leaving the blockIt 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'sawait usingandSymbol.asyncDispose. Handy for connections, files, locks and subscriptions in tests.29. What does
(typeof users)[number]return ifusers: User[]?Correct answer:
UserIndexed access by
numberreturns the array element type or a union of tuple element types. A popular combo:const roles = [...] as const; type Role = (typeof roles)[number].30. What does the mapped type
{ [K in keyof T]: Box<T[K]> }produce ifTis the tuple[string, number]?Correct answer: The tuple
[Box<string>, Box<number>]A mapped type over
keyof T, whereTis a tuple or array type parameter, maps the elements and preserves tuple-ness, length and modifiers. This lets you type, for example,Promise.allvia{ [K in keyof T]: Awaited<T[K]> }.31. How do you get the element type of a
Set<T>orMap<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
inferon the patternSet<infer T>Sethas no numeric index signature, so[number]doesn't work. A conditional type withinferextracts the parameter of any generic:Map<infer K, infer V>,Promise<infer R>. There's no built-inElementTypeutility. HereIdisstring.32. What is the
declarekeyword 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').declaredoesn't produce any JS code.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-errorabove the line being checked@ts-expect-errorsuppresses 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-ignoreis always silent and hides problems. For assertions there'sexpectTypeOfin Vitest,tsd, and@ts-expect-errorin type-challenges.34. When is the double assertion
x as unknown as Tjustified?Correct answer: Almost never: only for a deliberate workaround backed by a check
A plain
asis forbidden between unrelated types; viaunknownyou 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. Why should you avoid the
Functiontype for callbacks?Correct answer: It accepts any function, and calls aren't checked
Functiondescribes any function, and calling it is unsafe. Prefer a precise signature(value: string) => void, and for "any function" use(...args: never[]) => unknownor(...args: any[]) => any. Likewise,Objectand{}are better replaced withobjectorunknown.36. Why can't you write
a.xfora: { x: string } | { y: number }?Correct answer: Only common properties are accessible; narrow with
inThe compiler doesn't know which member
ais, and the second has nox. Afterif ('x' in a)the type is narrowed. Alternatives are a common discriminant (kind) or an explicitx?: undefinedin the second member.37. What does the
exactOptionalPropertyTypesflag change?Correct answer:
{ a?: string }rejects an explicita: undefinedWithout the flag,
a?: stringis equivalent toa?: string | undefined. With it, "no key" and "key present with valueundefined" are distinguished, which matters forObject.keys,inand spread. Ifundefinedis needed explicitly, writea?: string | undefined.38. What does
keyof (A | B)return ifA = { id; name }andB = { 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 distributekeyofover union members, use a conditional type:T extends any ? keyof T : never.39. How do you enable type checking in JS files without migrating to TS?
Correct answer:
// @ts-checkand types via JSDocTypeScript 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 viatsc --noEmit.40. How do you type a parameter that accepts an abstract class constructor?
Correct answer:
abstract new (...args: any[]) => TAbstract construct signatures (TS 4.2) let you accept both abstract and regular classes - e.g. in mixin functions.
new (...args) => Twon't accept an abstract class. There's no built-inConstructor<T>; people usually declare it themselves.41. Is the narrowing of a
letvariable 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
xmight be reassigned and reset the narrowing tostring | number. Since 5.4, the compiler understands the value is stable after the last assignment and keeps the narrowing. Forconstit already worked before.42. What is a homomorphic mapped type, and what does it preserve?
Correct answer: A
{ [K in keyof T]: ... }type that preservesT's modifiersWhen a mapped type iterates over
keyof Tdirectly, TS carries over the property modifiers ofT. That's whyPartial<Readonly<T>>stays readonly. When iterating over an arbitrary union of keys (K in 'a' | 'b'), modifiers aren't preserved.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 withAwaited<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 withanyor a singleTlose positional types.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. Why is
isolatedDeclarations(TS 5.5) useful for monorepos?Correct answer: It allows generating
.d.tsper file and in parallelThe 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.tsin parallel without waiting for a full check of dependencies.46. How does
T extends objectdiffer fromT 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, soT extends {}accepts'abc'and42. To allow only objects (including arrays and functions), useobject. For "anything except null/undefined",{}is exactly what you need.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 & Chas 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. How do you type a reducer so that
payloaddepends on the action'stype?Correct answer: Describe the actions as a union discriminated by the
typefieldtype Action = { type: 'add'; payload: Todo } | { type: 'remove'; payload: { id: string } }- incase 'add'TS knowspayloadis aTodo. Withneverindefaultyou get an exhaustiveness check. Redux Toolkit generates such types automatically fromcreateSlice.49. What does
T[keyof T]return forT = { a: string; b: number }?Correct answer:
string | numberIndexed 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. 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. 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
CatintoDog[]Accepting
readonly Animal[]in APIs that only read avoids the problem, since nothing can be written through it.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. 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
inferRouters like TanStack Router and typed Express helpers use this to make
params.idtype-safe.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. TypeScript has no higher-kinded types. How do libraries emulate
F<A>whereFis 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
OptionorArray.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: truein libraries and monorepos. Explicit return types also make declaration emit faster.57. Why does a dual ESM/CJS package need separate declaration files (e.g.
.d.mtsand.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. What does
rewriteRelativeImportExtensions(TS 5.7) enable?import { util } from './util.ts'; // emitted as './util.js'Correct answer:
.tsextensions in imports that work before and after compilingIt pairs with Node's type stripping: the same source runs directly and also compiles to correct JS imports.
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. What do the typescript-eslint
no-unsafe-*rules help with?Correct answer: Containing
any: they flag unsafe uses ofanyvaluesanyspreads silently through code. These rules force a conversion tounknownor a validated type at the boundary.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. What does a
this ispredicate 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
trueCalling
if (node.isLeaf())narrowsnodeinside the branch, like a regular type guard.63. What is
{ id: string } & { id: number }?Correct answer: A type where
idisnever, so no value fitsConflicting intersections don't fail immediately; errors appear later in confusing places. Prefer
interface extends, which reports conflicts at once.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. Why do excess property checks miss errors in this case?
const input = { name: 'A', nmae: 'typo' }; const user: User = input; // no errorCorrect answer: The checks apply only to fresh object literals
TypeScript has no exact object types. Assign literals directly, or use
satisfiesat the literal to keep the check.66. Why can a large union of string literals slow down the compiler?
Correct answer: Many operations scale with the number of members
Prefer
stringwith branded or validated types where unions grow into the thousands; check with--extendedDiagnostics.67. Why can a
letvariable lose its narrowing inside a callback but aconstkeeps it?Correct answer: A
letmay be reassigned before the callback runsRecent versions preserve narrowing for
letin closures created after the last assignment, but copying into aconstis the simple fix.68. Why should a public library avoid
enumin its API?Correct answer: They're nominal and emit runtime code
A union of string literals (with an
as constobject if you need runtime values) is erasable and friendlier to consumers.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 Tin the return typeCallers keep autocompletion and typo checks on keys. Note
Object.entriesinside still loses key types and needs a cast.70. How do you prevent consumers from depending on internal types of your library?
Correct answer: A deliberate API:
exportsplus stripped@internaltypesEvery exported type becomes part of the semver contract; a smaller surface makes changes safer.
71. What problem can
strictNullChecks: falsein one package cause in a monorepo?Correct answer: Emitted types may omit
null, giving false guaranteesConsistent strictness across packages, via a shared base config, prevents type information from being lost at boundaries.
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
TpreciseCasting (
(i as any).id) hides mistakes; the constraint documents and checks the requirement.73. What does
Object.freezereturn in terms of types?const config = Object.freeze({ mode: 'dark', retries: 3 });Correct answer: A shallow
Readonly<...>with literal primitivesNested objects are neither frozen at runtime nor readonly in the type.
as constmakes all levels readonly at the type level only.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 tablesLookup objects complement
switch+neverchecks: both make new union members fail loudly at compile time.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
TcompilesGenerate types from an OpenAPI schema or validate responses with a schema so the declared type matches reality.