PrepStack › Frontend › TypeScript

TypeScript interview cheat sheet

Type system, narrowing, generics, type-level tricks and typing React

TypeScript rounds test whether you can model data with types rather than just add : string everywhere. Expect questions on any vs unknown, interface vs type, narrowing and discriminated unions, generics with constraints, utility types (often “implement Pick yourself”), conditional types with infer, satisfies, tsconfig strictness and typing React components. Read the 15-minute revision first, then use Quiz mode. The snippets use @ts-expect-error to prove which lines fail to compile.

15-minute revision

  1. TypeScript is a compile-time layer over JavaScript. Types are erased, so they never change runtime behaviour or exist at runtime.
  2. Typing is structural: if the shape fits, it is assignable. Names do not matter. Fresh object literals also get an excess property check.
  3. any turns checking off. unknown is the safe top type: you must narrow it before use. never is the empty type (impossible values, exhaustive checks). void means “return value is ignored”.
  4. interface can be merged and extended; type can alias anything (unions, tuples, mapped and conditional types). For object shapes either works.
  5. Narrowing tools: typeof, instanceof, in, equality, truthiness, discriminated unions (a shared literal kind field), x is T predicates and asserts x is T functions.
  6. Exhaustive check: in the default branch assign the value to never. Adding a new union member then becomes a compile error.
  7. Generics are type parameters. Constrain them with extends (K extends keyof T). Return T[K] for typed property access.
  8. keyof T gives a union of keys, typeof x lifts a value into a type, T[K] is an indexed access type. (typeof arr)[number] gives the element type.
  9. Utility types are just mapped/conditional types: Partial, Required, Readonly, Pick, Omit, Record, Exclude, Extract, NonNullable, ReturnType, Parameters, Awaited.
  10. Conditional types distribute over unions when the checked type is a naked type parameter. Wrap in [T] to stop it. infer captures a part of a matched type.
  11. Prefer as const objects or string-literal unions over enums. Numeric enums are reverse-mapped and loosely typed; const enum breaks with isolated per-file transpilers.
  12. satisfies checks a value against a type without widening it. An annotation (: T) replaces the inferred type with T.
  13. private is compile-time only; #field is real JS privacy. abstract classes cannot be instantiated. Parameter properties (constructor(public x: number)) declare and assign in one go.
  14. strict: true enables strictNullChecks, noImplicitAny, strictFunctionTypes and more. Add noUncheckedIndexedAccess for safer arrays. In TS 6.0+ strict is on by default.
  15. TypeScript 7 (July 2026) is a native Go port of the compiler, roughly 10x faster, with the same type system. TS 6.0 was the bridge release that deprecated old options.
  16. React: type props with an interface, children: React.ReactNode, events as React.ChangeEvent<HTMLInputElement>, useState<User | null>(null), useRef<HTMLDivElement>(null).

Foundations

Why TypeScript & structural typing

TypeScript adds a static type checker on top of JavaScript; it compares shapes, not names, and erases every type at build time.

  • TypeScript is a superset of JavaScript: valid JS is (mostly) valid TS. The compiler checks types and then emits plain JS with the types removed.
  • Benefits: bugs caught before running, safe refactors, editor autocomplete and go-to-definition, and types that act as up-to-date documentation.
  • Structural typing (duck typing at compile time): a value fits a type if it has the required properties with compatible types. A class instance and a plain object with the same shape are interchangeable.
  • Excess property check: a fresh object literal passed straight to a typed slot cannot have unknown properties. The same object through a variable is allowed. It catches typos.
  • Type erasure: no types exist at runtime, so you cannot do if (x is User) at runtime. You need real JS checks (typeof, in, schema validation) for external data.
  • The type system is intentionally not fully sound (e.g. array covariance, any, type assertions). It trades soundness for practicality.

Interview questions

  • What is TypeScript and why use it?
  • What does “structural typing” mean?
  • Why is { x: 1, y: 1, label: 'b' } an error but the same object in a variable is fine?
  • Does TypeScript make your app type-safe at runtime?

Primitives, any, unknown, never & void

unknown is the safe version of any; never means “cannot happen”; void means “ignore the return value”.

  • Primitive types: string, number, bigint, boolean, symbol, null, undefined. Use lower case; String/Number are wrapper object types.
  • any disables type checking for a value and spreads: anything you read from it is also any. Treat it as an escape hatch.
  • unknown accepts any value, but you cannot use it until you narrow it. Use it for JSON.parse results, catch variables and untrusted input.
  • never has no values. It is the return type of functions that always throw or loop forever, the result of impossible intersections (string & number) and the tool for exhaustive checks.
  • void is the return type of functions whose result should be ignored. At runtime they return undefined.
  • With strictNullChecks, null and undefined are separate types. string no longer includes them, so you must write string | null.

Interview questions

  • Difference between any and unknown?
  • What is never and where is it used?
  • Difference between void and undefined as a return type?
  • What does strictNullChecks change?

interface vs type alias

Both describe object shapes; interface merges and extends, type can name any type expression.

  • interface describes object shapes (and classes, functions). It supports extends and declaration merging: two interface User blocks become one.
  • type gives a name to any type: unions, tuples, primitives, function types, mapped and conditional types.
  • Extending: interface B extends A {} vs type B = A & {}. Conflicting members in extends are a clear error; in an intersection they silently become never.
  • Declaration merging is how libraries let you augment global types such as Window or Express.Request.
  • Many teams use interface for public object shapes and type for unions and computed types. Pick one rule and be consistent.

Interview questions

  • Difference between interface and type?
  • What is declaration merging?
  • What happens when an intersection has conflicting property types?

Unions, intersections & literal types

A | B is “either”, A & B is “both”; literal types like 'GET' restrict a value to exact strings or numbers.

  • A union string | number accepts either. You can only use members that exist on every branch until you narrow.
  • An intersection A & B must satisfy both. It is used to combine object types or add fields (T & { id: string }).
  • Literal types: 'GET', 42, true. A union of literals ('sm' | 'md' | 'lg') is the idiomatic replacement for many enums.
  • Widening: let m = 'GET' is string; const m = 'GET' is 'GET'. Object properties widen too, because they can be reassigned.
  • as const makes literals readonly and keeps their literal types, for objects and arrays (tuples).
  • Tuples are fixed-length arrays with per-position types: [string, number], optional [string, number?] and labelled [name: string, age: number].

Interview questions

  • Difference between a union and an intersection type?
  • What is type widening?
  • What does as const do?

Narrowing & functions

Narrowing & discriminated unions

Control-flow analysis narrows a union inside each branch based on runtime checks you write.

  • typeof narrows primitives ('string', 'number', 'object', 'function'...). Remember typeof null === 'object'.
  • instanceof narrows to a class; 'key' in obj narrows to union members that have that key.
  • Equality (=== null, === 'circle') and truthiness (if (x)) narrow too. Truthiness also drops 0 and '', which may be a bug.
  • Discriminated (tagged) union: every member has a common literal field like kind. Switching on it narrows to the exact member.
  • Exhaustiveness: in default, assign the value to a never variable. If someone adds a member, that line stops compiling.
  • Narrowing is reset by assignments and does not survive into callbacks for let variables. Copy to a const first.

Interview questions

  • What is type narrowing?
  • What is a discriminated union and why is it useful?
  • How do you make a switch exhaustive?
  • Why might narrowing be lost inside a callback?

Custom type guards & assertion functions

x is T predicates narrow in an if; asserts x is T functions narrow everything after the call or throw.

  • A type predicate function isCat(x: unknown): x is Cat returns boolean, and when true the caller's variable is narrowed to Cat.
  • The compiler trusts your predicate. If the body is wrong, the types lie. Keep guards small and tested.
  • An assertion function asserts v is string throws when the check fails. After the call, v is narrowed for the rest of the scope.
  • asserts cond (no type) narrows based on a boolean condition, like Node's assert.
  • Since TS 5.5, simple predicates are inferred: arr.filter(x => x !== null) returns T[] without null.
  • Assertion functions must be called through an explicitly typed reference (a function declaration or an annotated const).

Interview questions

  • What is a user-defined type guard?
  • Difference between a type guard and an assertion function?
  • Is a type predicate checked by the compiler?

Function types & overloads

Type parameters and return values, use optional/default/rest params, and add overload signatures when the return type depends on the arguments.

  • Function type syntax: (a: number, b: number) => number. Object form with a call signature: { (a: number): number; label: string }.
  • Optional params b?: number, defaults b = 1 (type inferred) and rest ...xs: number[]. Optional params come last.
  • A function with fewer parameters is assignable to a type with more. That is why arr.forEach(x => ...) works without index and array.
  • Overloads: several signatures followed by one implementation. Callers only see the overload signatures, not the implementation signature.
  • Prefer a union parameter or a generic over overloads when the return type does not change with the input.
  • Declare a this parameter (function f(this: Window)) to type this; it is erased in the output.

Interview questions

  • What are function overloads and when would you use them?
  • Why can you pass a 1-parameter callback where a 3-parameter one is expected?
  • What is the difference between ? optional and | undefined?

Generics & constraints

Generics are type parameters that keep the link between inputs and outputs; extends limits what callers can pass.

  • A generic function first<T>(xs: T[]): T works for any T while preserving the exact type. Callers rarely pass T; it is inferred.
  • Constraints: T extends { length: number } lets you use .length inside. K extends keyof T limits a key to real keys of T.
  • Defaults: interface ApiResponse<D = unknown>. Generic classes and interfaces work the same way.
  • const type parameters (TS 5.0): function f<const T>(x: T) infers literal/tuple types as if the caller wrote as const.
  • NoInfer<T> (TS 5.4) stops a parameter from being used as an inference source, e.g. a defaultValue that must match the list.
  • Do not add a generic that appears only once. function log<T>(x: T): void is just (x: unknown) => void.

Interview questions

  • What are generics and why use them instead of any?
  • What does K extends keyof T mean?
  • What are const type parameters?
  • When should you not use a generic?

keyof, typeof & indexed access types

typeof turns a value into a type, keyof gives its keys, and T[K] reads a property type.

  • typeof config in a type position gives the inferred type of a value. It lets one runtime object be the single source of truth.
  • keyof T is the union of T's property names. For an index signature { [k: string]: X } it is string | number.
  • Indexed access T['port'], T[keyof T] (union of all value types) and Arr[number] (element type).
  • (typeof ROLES)[number] with ROLES = [...] as const gives a union of the literal values.
  • Object.keys(obj) returns string[], not (keyof T)[], because objects may have extra keys at runtime (structural typing).

Interview questions

  • Difference between typeof in JavaScript and in a TypeScript type?
  • Why does Object.keys return string[] and not (keyof T)[]?
  • How do you derive a union type from an array of strings?

Type-level programming

Utility types & how they are built

Built-in helpers like Partial, Pick, Omit and ReturnType are a few lines of mapped and conditional types; be ready to write them.

  • Shape modifiers: Partial<T>, Required<T>, Readonly<T>. They change modifiers on every property (shallowly).
  • Selecting: Pick<T, K> keeps keys, Omit<T, K> removes keys, Record<K, V> builds an object type from a key union.
  • Union filters: Exclude<U, X> removes members, Extract<U, X> keeps them, NonNullable<T> drops null/undefined.
  • Function helpers: ReturnType<F>, Parameters<F>, ConstructorParameters<C>, InstanceType<C>.
  • Awaited<T> unwraps promises recursively, the way await does. ReturnType<typeof fetchUser> + Awaited gives the resolved data type.
  • Others: NoInfer<T>, ThisType<T>, and string helpers Uppercase, Lowercase, Capitalize, Uncapitalize.

Interview questions

  • Implement Pick and Omit.
  • Difference between Pick/Omit and Extract/Exclude?
  • How do you get the resolved type of an async function's result?
  • Is Partial<T> deep?

Mapped types & key remapping

{ [K in Keys]: ... } loops over a key union to build a new object type, with control over modifiers and key names.

  • { [K in keyof T]: T[K] } copies T. Change the right side to transform values, e.g. T[K] | null.
  • Modifiers: add or remove readonly and ? with +/-: -readonly makes a type mutable, -? makes properties required.
  • Mapped types over keyof T are homomorphic: they keep the original optional/readonly modifiers.
  • Key remapping with as (TS 4.1): [K in keyof T as NewKey]. Map a key to never to filter it out.
  • Combine with template literal types to generate names like getName, onChange, setValue.

Interview questions

  • What is a mapped type?
  • How do you remove readonly or ? from all properties?
  • How do you filter properties by their value type?

Conditional types & infer

T extends U ? X : Y is an if/else for types; it distributes over unions and can capture parts with infer.

  • T extends U ? X : Y checks assignability at the type level. It is evaluated when T is known, so generic results stay deferred until then.
  • Distribution: if T is a naked type parameter and you pass a union, the condition runs per member and the results are unioned.
  • Stop distribution by wrapping both sides in a tuple: [T] extends [U]. Needed for checks like IsNever<T>.
  • never is an empty union, so a distributive conditional over never returns never.
  • infer X declares a type variable inside the extends clause to capture part of the matched type (element, return, promise value).
  • Conditional types can be recursive (DeepReadonly, Awaited, string parsers). The compiler has depth limits, so keep recursion shallow.

Interview questions

  • What is a conditional type?
  • What are distributive conditional types?
  • What does infer do?
  • Why does IsNever<never> written as T extends never ? true : false return never?

Template literal types

Backtick types build and parse string literal types, e.g. event names, CSS units and route params.

  • Written with backticks at the type level: a template like on${Capitalize<Name>} builds new string literal types from other literals.
  • Interpolating unions produces the cross product: 2 sizes × 2 colors = 4 variant names.
  • Intrinsic helpers: Uppercase, Lowercase, Capitalize, Uncapitalize.
  • With infer you can parse strings: extract route params from '/users/:id' or split on a dot.
  • Pattern types: the template /${string} accepts any string that starts with a slash, and ${number}px accepts '12px'.

Interview questions

  • What are template literal types?
  • How would you type route params from a path string?

Language features

Enums vs literal unions & as const

Enums create real runtime objects; most teams now prefer string-literal unions or as const objects.

  • Numeric enums auto-increment from 0 and get a reverse mapping (Direction[0] === 'Up'), so Object.keys shows both numbers and names.
  • String enums have no reverse mapping and are nominal: you cannot pass the raw string 'ACTIVE' where Status is expected.
  • const enum is inlined at compile time and leaves no object, but breaks under isolatedModules and single-file transpilers across files.
  • Enums are one of the few TS features with runtime output, so Node's type stripping and erasableSyntaxOnly (TS 5.8) reject them.
  • Alternative: an as const object for runtime values plus a derived union type. It is plain JS, tree-shakes well and accepts raw strings.

Interview questions

  • Enum vs union of string literals: which do you prefer?
  • What is a reverse mapping?
  • What is a const enum and what is the catch?

satisfies, assertions & non-null

satisfies validates without changing the inferred type; as overrides the checker; ! removes null without checking.

  • An annotation const x: T = ... sets the variable's type to T. You lose more specific information from the value.
  • value satisfies T (TS 4.9) checks the value against T, including excess properties, but keeps the inferred type.
  • Combine as const satisfies T to get literal readonly types plus validation, great for config and route maps.
  • A type assertion x as T tells the compiler to trust you. It only allows assertions between related types; as unknown as T forces anything.
  • The non-null assertion x! removes null | undefined. It does nothing at runtime, so a wrong ! crashes later.
  • Prefer narrowing over assertions. Use as mainly at boundaries (e.g. document.getElementById('x') as HTMLInputElement).

Interview questions

  • What does satisfies do and how is it different from a type annotation?
  • Difference between as and satisfies?
  • What is the non-null assertion operator?

Classes, access modifiers & abstract

TS adds public/private/protected, readonly, parameter properties, abstract and implements on top of JS classes.

  • public (default), protected (class + subclasses), private (class only). These are compile-time checks only.
  • #field is a JS private field: enforced at runtime, invisible to Object.keys and JSON.stringify.
  • Parameter properties: constructor(private readonly id: string) declares and assigns the field in one step.
  • abstract class cannot be instantiated; abstract methods must be implemented by subclasses. It can also hold shared code.
  • implements Interface only checks the class shape; it does not add any code or inherit anything.
  • override keyword (with noImplicitOverride) catches methods that no longer override anything after a base class rename.

Interview questions

  • Difference between private and #private?
  • Difference between an abstract class and an interface?
  • What are parameter properties?

Project setup

Modules & declaration files

.d.ts files describe the types of JavaScript code; declare adds types without emitting code; augmentation extends existing types.

  • A file with a top-level import/export is a module; otherwise it is a global script whose declarations leak into the global scope.
  • .d.ts files hold only types. Libraries ship them ("types" in package.json) or you get them from DefinitelyTyped (@types/react).
  • declare describes something that exists at runtime but was not written in TS: declare const VERSION: string, declare module 'legacy-lib'.
  • declare module '*.svg' types non-JS imports for bundlers. Module augmentation adds members to an existing module's interfaces.
  • declare global { interface Window { ... } } inside a module augments globals.
  • import type / export type are erased completely; required with verbatimModuleSyntax so transpilers know what to drop.

Interview questions

  • What is a .d.ts file?
  • What does the declare keyword do?
  • How do you add a property to the global Window or a library type?
  • What is the difference between import type and a normal import?

tsconfig & strict mode

strict: true turns on the important safety checks; a few extra flags catch even more, and TS 6/7 changed several defaults.

  • strict is a bundle: strictNullChecks, noImplicitAny, strictFunctionTypes, strictBindCallApply, strictPropertyInitialization, noImplicitThis, alwaysStrict, useUnknownInCatchVariables, strictBuiltinIteratorReturn.
  • Popular extras: noUncheckedIndexedAccess (index reads include undefined), exactOptionalPropertyTypes, noImplicitOverride, noFallthroughCasesInSwitch.
  • target sets the JS syntax output; lib sets which built-in APIs are typed (DOM, ES2023); module + moduleResolution decide how imports are resolved (bundler, nodenext).
  • For bundler apps: noEmit: true, moduleResolution: "bundler", isolatedModules / verbatimModuleSyntax, jsx: "react-jsx".
  • skipLibCheck skips checking .d.ts files in dependencies to speed up builds.
  • TS 6.0 made strict default to true, module default to esnext, types default to [], and deprecated target: es5, baseUrl and moduleResolution: node. TS 7.0 removed those deprecated options.

Interview questions

  • What does strict: true enable?
  • What does noUncheckedIndexedAccess do and why is it not in strict?
  • Difference between target and lib?
  • What changed in TypeScript 6 and 7?

React & puzzles

Typing React components & hooks

Type props with an interface, let hooks infer where they can, and give explicit generics for useState unions, refs, reducers and context.

  • Props: a plain function function Button({ label }: ButtonProps). React.FC is optional and no longer adds implicit children (React 18 types).
  • children: React.ReactNode accepts anything renderable. React.ReactElement is narrower (only JSX elements).
  • Events: React.ChangeEvent<HTMLInputElement>, React.MouseEvent<HTMLButtonElement>, React.FormEvent<HTMLFormElement>. Inline handlers infer it for you.
  • useState<User | null>(null) needs the generic because null alone would infer null. useRef<HTMLInputElement>(null) for DOM refs.
  • Extend native props: React.ComponentProps<'button'> or React.ButtonHTMLAttributes<HTMLButtonElement>, then Omit what you override.
  • Generic components (function List<T>(props: ListProps<T>)) keep item types flowing into renderItem. Reducers work best with a discriminated-union Action type.

Interview questions

  • How do you type a component's children?
  • Should you use React.FC?
  • How do you type useState when the initial value is null?
  • How do you build a component that accepts all native button props plus your own?
  • How do you write a generic List component?

Output & compile-error puzzles

Most TypeScript trick questions come from erasure, unsound spots and inference rules.

  • Array covariance: Dog[] is assignable to Animal[], so you can push a cat into a dog array through the wider reference.
  • Index access on arrays and records is typed as the element type, even if the item does not exist (unless noUncheckedIndexedAccess).
  • Assertions do not convert: '42' as unknown as number is still a string, so + 1 concatenates.
  • Optional property x?: number may be missing entirely; 'x' in o is false.
  • Excess property checks only apply to fresh literals. readonly and private vanish at runtime.
  • Object.keys returns string[], so indexing a typed object with its result fails to compile.

Interview questions

  • Is TypeScript's type system sound? Give an example.
  • What prints: const n = '42' as unknown as number; console.log(n + 1)?
  • Why does p[k] fail inside for (const k of Object.keys(p))?
  • If readonly prevents push, why can the array still change?