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.
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 Tthat narrows the argument whentrueAfter
if (isUser(data)),datahas typeUserinside 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. forarr.filter(x => x !== null).2. How do you guarantee that a
switchhandled 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
defaultto a variable of typeneverIf you add a new shape to
Shapeand forget acase, a non-empty type remains indefault, and assigning it tonevercauses a compile error. ThenoImplicitReturnsflag and the ESLint ruleswitch-exhaustiveness-checkalso help.3. What does
<T extends { id: string }>mean in a generic?Correct answer: A constraint:
Tmust have at least anid: stringpropertyA constraint lets you safely access
item.idinside the function while keeping the full typeTin the result. You can pass any object with a suitableidand other fields. Classes and inheritance have nothing to do with it.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 Tallows only existing keys, and the indexed accessT[K]gives the exact value type:getProp(user, 'age')→number. Theanyversion loses typing, andstringlets typos through.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 withas.Partial,ReadonlyandRecordare built on mapped types.6. What does the conditional type
T extends string ? 'text' : 'other'do?Correct answer: Picks one of the types depending on whether
Tis assignable tostringConditional 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. What does
inferdo intype ElementType<T> = T extends (infer U)[] ? U : never?Correct answer: Declares a type variable
Uthat TS infers from matching the patterninferis used only in theextendspart of a conditional type: TS matchesTagainst the pattern and "captures" the needed part.ElementType<string[]>→string. That's howReturnType,ParametersandAwaitedwork.8. What does
Awaited<Promise<Promise<number>>>return?Correct answer:
numberAwaitedrecursively unwraps promises and thenables, mirroring the behavior ofawait. Handy for an async function's result type:Awaited<ReturnType<typeof fetchUser>>.9. How does
Exclude<T, U>differ fromOmit<T, K>?Correct answer:
Excluderemoves members from a union,Omitremoves properties from an object typeExclude<'a' | 'b' | 'c', 'a'>→'b' | 'c'.Omit<User, 'password'>→ an object without the field. Paired utilities:Extract(keep matching union members) andPick(keep properties).NonNullable<T>removesnullandundefined.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. What is declaration merging?
Correct answer: Combining same-named declarations, e.g. two
interface Windows, into oneInterfaces, namespaces and some other declarations with the same name merge. That's how global types are extended:
interface Window { analytics: Analytics }indeclare global.typealiases don't merge - redeclaring one is an error.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 implementfindand getlogready-made. Unlike an interface, an abstract class exists at runtime and can contain code and state.13. How does
protecteddiffer fromprivatein TypeScript classes?Correct answer:
protectedis open to subclasses,privateisn'tpublic(the default) is accessible everywhere,protectedin the class and its subclasses,privateonly in the declaring class. All three are compiler checks; for real runtime privacy there's#field.14. What does the
satisfiesoperator 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.greenwould becomestring | number[]. Withsatisfies, the shape is checked, butpalette.greenstaysstring, so you can call.toUpperCase(). Unlikeas, nothing is asserted without a check.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. Why is an
as constobject often used instead of anenum?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. How does
const enumdiffer from a regularenum?Correct answer: Values are inlined at compile time; there's no object at runtime
const enumsaves bundle size but doesn't play well withisolatedModulesand 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. 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, whiledeclare namespaceis sometimes used in declarations to describe global libraries. Namespaces aren't compatible witherasableSyntaxOnly.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),valueis astringfor the rest of the code, with noif. 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. How do you get a typed
e.detailinwindow.addEventListener('cart:add', (e) => ...)for your own event?Correct answer: Add the event to
WindowEventMapviadeclare globaladdEventListenerlooks up the event type by name inWindowEventMap(andDocumentEventMap,HTMLElementEventMap). Declaration merging adds your entry:interface WindowEventMap { 'cart:add': CustomEvent<{ id: string }> }insidedeclare global. Thene.detail.idis astringin every listener. Nothing is inferred fromdispatchEventcalls.21. Why should
groupByreturnPartial<Record<K, T[]>>rather thanRecord<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
Kis guaranteed to appear in the resultIf there are no
donetasks,byStatus.doneisundefined, yetRecord<K, T[]>claims an array is always there, andbyStatus.done.lengthcrashes.Partialmakes the valuesT[] | undefinedand forces a check. The built-inObject.groupByis typed exactly this way.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
setTimeoutreturns anumber, in Node.js aTimeoutobject, and when bothdomand@types/nodeare loaded, the Node signature often wins.ReturnType<typeof setTimeout>takes whatever the current environment declares, soclearTimeout(timer)type-checks everywhere.23. What does
Extract<'a' | 'b' | 1 | 2, string>produce?Correct answer:
'a' | 'b'Extract<T, U>keeps the union members assignable toU- here, the string literals. The oppositeExcludewould keep1 | 2. Both utilities are distributive conditional types.24. What does
NonNullable<string | null | undefined>return?Correct answer:
stringNonNullable<T>excludesnullandundefinedfrom a union. It's currently implemented asT & {}. Handy for values after a check or infilterresults.25. How do
object,{}andRecord<string, unknown>differ as types?Correct answer:
{}non-null,objectnon-primitive,Recorda dictionary{}accepts strings and numbers too - everything exceptnullandundefined, which often surprises people.objectexcludes primitives.Record<string, unknown>is an object with arbitrary string keys whose values you can access. For "any value",unknownis better.26. How does TypeScript handle the
inoperator 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
swimpropertyTS supports narrowing via
typeof,instanceof,in, equality checks, truthiness and discriminants. Inelse,Birdremains. For network data, such checks are part of runtime validation.27. What do
-readonlyand-?do in a mapped type?type Mutable<T> = { -readonly [K in keyof T]-?: T[K] };Correct answer: Remove the
readonlyand?modifiers from all propertiesThe
-prefix removes a modifier,+(the default) adds it. That's howRequired<T>is implemented (-?). There's no built-inMutable, but it's often written following this pattern.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
asafterin, using a template literalKey remapping (TS 4.1+):
Getters<{ name: string }>→{ getName: () => string }. If the expression afterasproducesnever, the key is dropped - that's how properties are filtered by value type.string & Kis needed because keys can be symbols or numbers.29. Why does
Object.keys(user)returnstring[]rather than(keyof User)[]?Correct answer: At runtime the object may have other keys too
An object of type
Usermay 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. What does the
noUncheckedIndexedAccessflag give you?Correct answer: Index access gets a type with
| undefinedWithout the flag,
const x = arr[10]is typed asT, even though it'sundefinedat runtime. With the flag, the compiler makes you check the value. The flag isn't part ofstrict, but it's often recommended.31. How does
unknown[]differ fromany[]in a function parameter?Correct answer: With
unknown[]elements must be narrowed, withany[]they don'tBoth accept any array, but inside a function with
unknownyou 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 genericT[]if the type matters for the result.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. 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
verbatimModuleSyntaxflag, this is mandatory for types. It also avoids unwanted side effects from loading the module.34. Why is
interfacepreferable to an intersection for extending large object types?Correct answer:
extendscatches property conflicts and is faster for the compilerWith
interface B extends A, a property conflict is an error at the declaration, while an intersection silently producesnever. The compiler caches interface relationships, so it's faster in large codebases - as the TS performance wiki recommends.35. What does
Parameters<(a: string, b?: number) => void>return?Correct answer:
[a: string, b?: number]Parametersreturns a tuple of parameters, preserving optionality and names. Handy for wrappers:function logged(...args: Parameters<typeof fn>). For constructors there'sConstructorParameters.36. How do you specify the type of
thisfor 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 compileThe
thispseudo-parameter describes which context the function must be called with; it isn't an argument. The compiler checks calls and uses ofthisinside. In arrow functions,thisis lexical and can't be specified this way.37. What's the best way to type an API response whose structure differs by status?
Correct answer: A union discriminated by
ok: success withdataor an errorA union makes impossible states unrepresentable: with
ok: true,datais guaranteed anderrorisn't available. A type with optional fields allows meaningless combinations and requires checks everywhere.38. What does the
ReadonlyArray<T>utility (orreadonly T[]) do?Correct answer: Removes mutating methods (
push,sort) from the typeA
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. What is
unique symbol?Correct answer: The type of a specific symbol declared via
const s = Symbol()Each
constwithSymbol()gets its ownunique symbolsubtype, so TS distinguishes such keys. This is used for "hidden" properties and type branding. A plainsymboldescribes any symbol.40. How do you extend the type of the global
Windowobject from a module?export {}; declare global { interface Window { dataLayer: unknown[] } }Correct answer: With
declare globaland merging into theWindowinterfaceIn a module file (with
import/export), global declarations go insidedeclare global. TheWindowinterface merges with your extension. Redeclaringtype Windowcauses a duplicate identifier error.41. How do you type the result of
JSON.parsesafely?Correct answer: Treat the result as
unknownand validate it with a schema (Zod)JSON.parsereturnsany, but external data may not match expectations. A schema (z.object({...})) validates data at runtime, andz.infer<typeof schema>gives a TS type without duplication.as Useronly hides the problem.42. How does
type A = Bdiffer frominterface 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. What does
pathsintsconfig.jsongive you?Correct answer: Import path aliases, e.g.
@/*→./src/*pathslets you writeimport { 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 byinclude, output byoutDir.44. How does
moduleResolution: 'bundler'differ from'node16'/'nodenext'?Correct answer:
bundlermimics bundlers,nodenextfollows Node.jsIn Node.js ESM you must write extensions in relative imports and account for
exports/type. Bundlers (Vite, Next.js, esbuild) are forgiving about this, andbundlermode mirrors their behavior. For code run by Node.js without a build step, choosenodenext.45. What does the
isolatedModulesflag 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.
isolatedModuleswarns about code they can't handle correctly: re-exporting a type withoutexport type, accessing aconst enumfrom another file, and so on.46. What does
keyof typeof objdo?const routes = { home: '/', about: '/about' }; type RouteName = keyof typeof routes;Correct answer: Gets the union of the
routesvalue's keys:'home' | 'about'typeof routesgives the object's type, andkeyofits keys. For a union of values you need indexed access:typeof routes[keyof typeof routes], andas constto make the values literals.47. When does TS widen a literal type to a general one?
Correct answer: In mutable positions:
let, object propertiesconst a = 'x'→'x', butlet 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 orsatisfies.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:
Boxwithout an argument isBox<string>. They can be combined with constraints:<T extends object = {}>. That's how, for example,useState<S = undefined>andEventEmitter<T = any>work.49. How do you type a factory function that returns the same type it received?
Correct answer:
function clone<T>(value: T): TA generic preserves the link between input and output:
clone(user)returns aUser. Withanyandobject, the calling code loses type information and has to cast.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 ofe(MouseEvent) is inferred from theaddEventListenersignature.mapcallbacks, JSX handlers anduseStatesetters work the same way. If you move the function into a separate variable, the context is lost - you'll have to annotate it.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:
Omitsees only common keys; it isn't distributivekeyof (A | B)contains only shared keys, so member-specific properties disappear. The conditional type distributes over the union.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 routesstays'home' | 'user', and a typo in a property is still reported.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. 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
erasableSyntaxOnlyand by runtimes that only strip types.55. What do the
overridekeyword andnoImplicitOverrideprotect against?Correct answer: Accidental overrides and overrides left after a base rename
With the flag, every overriding member must say
override, andoverrideon a member that doesn't exist in the base class is an error.56. Why might
Readonly<Settings>not prevent this change?const s: Readonly<Settings> = load(); s.theme.colors.primary = 'red';Correct answer:
Readonlyis shallow; nested objects stay mutableA recursive
DeepReadonlytype oras constfor literals protect nested levels at the type level.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 truthValidation at the boundary (API, forms) plus inferred types avoids drift between runtime checks and compile-time types.
58. What does type-aware linting with typescript-eslint add on top of
tsc?Correct answer: Rules using type info, e.g. floating promises
tscchecks type correctness; lint rules likeno-floating-promisescatch bugs that are type-correct but likely wrong.59. How do you share one strict base configuration between many packages?
{ "extends": "@tsconfig/strictest/tsconfig.json", "include": ["src"] }Correct answer:
extendsin eachtsconfig.json, to a shared baseCommunity bases (
@tsconfig/node22,@tsconfig/strictest, ...) or an internal package keep settings consistent.60. How do
targetandlibdiffer intsconfig.json?Correct answer:
target: emitted JS syntax;lib: declared built-in APIslibdoesn't add polyfills: declaringES2023lets you callfindLast, but old browsers still need a polyfill.61. What does
esModuleInteropfix?import express from 'express'; // a CommonJS moduleCorrect 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. Which option lets you
import config from './config.json'with typed contents?Correct answer:
resolveJsonModuleTypeScript infers the type from the JSON file content. Values are widened (e.g. strings, not literals).
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:
InstanceTypeandConstructorParametersontypeof ClassApiServiceas a type already means the instance type;typeof ApiServiceis the constructor itself.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 predicatePromiseSettledResult<T>is a discriminated union of fulfilled (value) and rejected (reason) results.65. What do the intrinsic types
Uppercase,Capitalizeetc. 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/onClickfrom keys, keeping APIs consistent automatically.66. What do
noImplicitReturnsandnoFallthroughCasesInSwitchcatch?Correct answer: Missed returns and accidental
casefall-throughThey're not part of
strictbut catch common logic bugs cheaply.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 useAsyncGenerator<...>.68. What is the type of
errinpromise.catch((err) => ...)withstrictenabled?Correct answer:
any- the flag covers onlytry/catchblocksuseUnknownInCatchVariableschanges onlycatch (e)clauses. In thePromisetypes,onrejectedreceivesreason: any, soerr.messagecompiles even if a string was rejected. Annotate it yourself,(err: unknown) => ..., or usetry/catchwithawait.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 asV | undefined, which also forces handling missing keys.70. What do the
types/typesVersionsand theexports"types"condition inpackage.jsondo?Correct answer: Tell TypeScript where a package's declarations live
With
exports, put thetypescondition first in each entry, otherwise TypeScript may resolve the JS file and find no types.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
verbatimModuleSyntaxand type-only barrels.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. 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. 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
constdestructuringThe destructured variables must be
const(or unmodified parameters) for control-flow analysis to connect them.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
casecondition narrows the value in its branchIt's a readable alternative to long
if/else ifchains with type guards.