Skip to content
Tech Interview Prep
Technical interview guideNew

TypeScript for Frontend Engineers

TypeScript's type system as frontend code actually uses it: structural typing, generics, narrowing, utility types, and typing React props, hooks and events. Plus what the compiler catches at build time, what it erases, and where runtime validation is still required.

Read
18 min
Practice MCQs
25
Interview Q&A
25
Edition
v1
Editorial status
Reviewed
Relevant for
Frontend Engineer

Scope: TypeScript 5.x (checked against 5.8), React 18 and 19 with @types/react 18/19. `satisfies` requires TS 4.9+; inferred type predicates require 5.5+; `verbatimModuleSyntax` requires 5.0+. Defaults quoted are from the TS 5.8 `tsc --init` output..

Overview

Curated: · Written: · Reviewed:

TypeScript for frontend engineers

Senior frontend interviews rarely test whether you can write a type annotation. They test whether you understand the type system as a model of your program: what it proves at build time, what it erases, and where the boundary to runtime sits. Most hard TypeScript questions reduce to three: what the compiler checks, what it throws away, and what you must validate by hand.

The model to carry: TypeScript is a checker that runs before your code. Types are erased at build time, so a type can only make the compiler reject a program. It cannot make a running program safer.

Why TypeScript, and what it actually checks

tsc emits JavaScript with every annotation, interface and generic removed. The runtime sees the JS you would have written by hand. Two consequences follow. Types cost nothing at runtime, and they offer no protection at runtime. A User type does not validate a fetch response. It records what you assert the response is.

What the compiler catches:

  • Misspelled properties: user.nam fails when User has no nam.
  • Null dereferences: under strictNullChecks, maybeUser.name fails until you narrow.
  • Wrong prop shapes: { title: 42 } passed where title: string is required.
  • Refactor breakage: renaming a field fails every consumer still using the old name.
  • Missing union cases: a switch can be made to fail when a case is unhandled (shown below).

What it cannot catch:

  • Network data. r.json() returns Promise<any>. The compiler has no view of what the server sent.
  • any leaks. One any in a chain disables checking for every expression it touches.
  • Runtime-only invariants such as sorted arrays, IDs that exist in a database, or a mounted component.
  • Lying assertions. x as User compiles whether or not x is a User.
interface User { id: string; name: string }

const u: User = { id: "1", name: "Ada" };
u.nam;                 // error: Property 'nam' does not exist on type 'User'
const maybe: User | null = null;
maybe.name;            // error under strictNullChecks: 'maybe' is possibly 'null'

async function load(): Promise<User> {
  const r = await fetch("/api/user");
  return r.json();     // compiles: r.json() is Promise<any>, which is assignable
}

The last function is the lesson. load is declared to return Promise<User>, yet nothing checked the response. The annotation is a claim.

Interviewers probe: 'What does TypeScript not catch?' A weak answer lists syntax errors. A strong answer names the runtime boundary and any as the two leaks.

The mental model: structural typing, assignability, widening and variance

TypeScript compares types by shape. If A has every member B requires, A is assignable to B. No implements clause or registration is needed.

interface Point { x: number; y: number }
const p = { x: 1, y: 2, z: 3 };
const q: Point = p;                      // ok: p is a variable, extra keys are not visible through Point
const r: Point = { x: 1, y: 2, z: 3 };   // error: excess property check on an object literal

Object literals get the excess property check because a stray key in a literal is usually a typo. A variable with extra keys passes, because the extra keys are simply not visible through the target type.

Widening: let a = "on" infers string, since the binding can be reassigned. const b = "on" keeps the literal type "on". as const applies literal and readonly types at every level.

let a = "on";                    // string
const b = "on";                  // "on"
const c = { s: "on" };           // { s: string }
const d = { s: "on" } as const;  // { readonly s: "on" }

readonly is shallow and exists only at compile time. It blocks assignment through that view. A mutable alias can still change the object, and nothing stops runtime mutation.

Variance: under strictFunctionTypes, function parameters are checked contravariantly. A function that accepts a wider type can stand in for one that accepts a narrower type. Method syntax is checked bivariantly, which keeps Array<T> unsound in one direction.

type Handler = (e: MouseEvent) => void;
const h: Handler = (e: Event) => {};            // ok: Event is wider than MouseEvent
const bad: (e: Event) => void = (e: MouseEvent) => {}; // error under strictFunctionTypes

Interviewers probe: 'Why is Array<T> unsound?' Dog[] is assignable to Animal[]. Pushing a Cat through the Animal[] view then puts a Cat into a Dog[], and a later read believes it has a Dog. TypeScript accepts this for ergonomics. A readonly Animal[] parameter closes the hole for reads.

Modelling data: types vs interfaces, unions, enums vs const objects

type and interface are close substitutes for object shapes. They differ in three ways that matter:

  • Declaration merging: two interface Foo declarations merge. Two type Foo declarations are an error.
  • extends checks overrides strictly: interface B extends A fails on an incompatible member. type B = A & C does not fail. A conflicting member quietly becomes never.
  • Unions and mapped types can only be written with type.
interface A { x: string }
interface B extends A { x: number } // error: incompatible override
type C = A & { x: number };         // no error; C["x"] is never

Discriminated unions model frontend state. A shared literal field lets the compiler narrow the rest of the shape, so illegal combinations cannot be written.

type State =
  | { status: "idle" }
  | { status: "loading" }
  | { status: "success"; data: User }
  | { status: "error"; error: Error };

function render(s: State): string {
  switch (s.status) {
    case "idle": return "idle";
    case "loading": return "loading";
    case "success": return s.data.name; // s.data is User here
    case "error": return s.error.message;
  }
}

The boolean-flag version, { loading: boolean; data?: User; error?: Error }, accepts { loading: true, data: user, error: err }. That state should never exist, and the union version rejects it.

Enums: a numeric enum emits runtime code and a reverse mapping. const enum is problematic under isolatedModules. A const object with a union derived from it gives a runtime value and a literal union with no enum emit:

const Status = { Idle: "idle", Loading: "loading" } as const;
type Status = typeof Status[keyof typeof Status]; // "idle" | "loading"

Interviewers probe: 'When would you use an enum?' In application code, rarely. String-literal unions and as const objects give the same checking with less emit.

Generics: constraints, defaults, inference and generic components

A generic is a function over types. The compiler infers type arguments from the values you pass.

function first<T>(xs: T[]): T | undefined { return xs[0]; }
const n = first([1, 2, 3]); // T inferred as number; n: number | undefined

Constraints restrict T so its members can be used:

function pluck<T, K extends keyof T>(xs: T[], key: K): T[K][] {
  return xs.map(x => x[key]);
}
pluck([{ id: "1", name: "Ada" }], "name"); // string[]

Defaults apply when inference has nothing to work with:

type Box<T = string> = { value: T };
type S = Box; // Box<string>

In .tsx files, a generic arrow function needs a trailing comma or an extends clause. Without one, the parser reads <T> as a JSX opening tag.

function List<T,>({ items, render }: { items: T[]; render: (t: T) => React.ReactNode }) {
  return <ul>{items.map((it, i) => <li key={i}>{render(it)}</li>)}</ul>;
}

Interviewers probe: 'Why <T,>?' A weak answer calls it a TSX quirk. A strong answer explains the parser ambiguity and notes that <T extends unknown> also works.

Narrowing and control-flow analysis

The compiler tracks a binding's type through each branch. Each check removes possibilities until one remains.

function area(shape: Circle | Rect): number {
  if ("radius" in shape) return Math.PI * shape.radius ** 2; // Circle
  return shape.width * shape.height;                           // Rect
}

Narrowing operators:

  • typeof x === "string" narrows primitives.
  • x instanceof Date narrows class instances.
  • "k" in x narrows by property presence.
  • x.kind === "circle" narrows a discriminated union.
  • User-defined predicates, function isUser(x: unknown): x is User, make the compiler trust your check. The function body is not verified against the type.
  • Assertion functions, function assertUser(x: unknown): asserts x is User, narrow the rest of the enclosing scope on the same trust basis.

Exhaustiveness: after every case is handled, the leftover type is never. Passing it to a never parameter turns a missing case into a compile error.

function assertNever(x: never): never {
  throw new Error(`Unhandled: ${JSON.stringify(x)}`);
}
function label(s: State): string {
  switch (s.status) {
    case "idle": return "idle";
    case "loading": return "loading";
    case "success": return "done";
    default: return assertNever(s); // error if a status is added and not handled
  }
}

as bypasses this machinery. x as User is an unchecked assertion. It narrows nothing and emits no check, so it is the most common source of type lies in a codebase.

Interviewers probe: 'Difference between as and a type predicate?' A predicate is a function whose body you can test, and the compiler trusts its result at each call site. as has no body and no runtime counterpart.

Utility, mapped, conditional and template literal types

The built-in utilities are mapped and conditional types. Knowing the underlying forms lets you write your own.

type Partial<T> = { [K in keyof T]?: T[K] };
type Pick<T, K extends keyof T> = { [P in K]: T[P] };
type Omit<T, K extends keyof any> = Pick<T, Exclude<keyof T, K>>;
type Record<K extends keyof any, V> = { [P in K]: V };
type ReturnType<F> = F extends (...a: any) => infer R ? R : never;
type Awaited<T> = T extends Promise<infer U> ? Awaited<U> : T;

Key remapping with as in a mapped type:

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

infer captures a type inside a conditional. A conditional type applied to a naked type parameter distributes over unions, so Exclude<"a" | "b", "a"> is "b".

satisfies checks a value against a type without widening it:

const config = { mode: "dark", level: 3 } satisfies Config; // checked; mode stays "dark"
const frozen = { mode: "dark" } as const;                   // readonly literals, no check against a type
const annotated: Config = { mode: "dark", level: 3 };       // mode widens to the Config property type

Interviewers probe: 'Write DeepPartial.' A recursive mapped type does it. A strong answer mentions the cost: recursion over large or deeply nested types slows tsc, and an explicit depth cap keeps it bounded.

Typing React: props, hooks, events, context and refs

Props are an object type. children is React.ReactNode. Optional props use ? and must be handled at use sites.

type ButtonProps = {
  label: string;
  onClick?: () => void;
  children?: React.ReactNode;
};

function Button({ label, onClick, children }: ButtonProps) {
  return <button onClick={onClick}>{children ?? label}</button>;
}

React.FC once added children implicitly. Current React type definitions no longer do, so declare children in the props type. A plain function with a typed props parameter is clearer, because the props type stays visible.

useState needs an explicit type argument when the initial value is narrower than the intended union:

const [state, setState] = useState<State>({ status: "idle" });

Lazy initialiser: useState(() => expensive()) calls the function once, on mount. useState(expensive()) calls it on every render and discards the result after the first.

useRef<HTMLDivElement>(null) returns a ref whose current is typed HTMLDivElement | null and is read-only in the type. The nullability is correct: the node does not exist before mount and is null after unmount. Typing it as non-null would be a lie.

useReducer with a discriminated action union gives exhaustive handling:

type Action = { type: "inc" } | { type: "set"; value: number };
function reducer(state: number, action: Action): number {
  switch (action.type) {
    case "inc": return state + 1;
    case "set": return action.value;
  }
}

Event types take the element the handler is attached to as their generic parameter: React.ChangeEvent<HTMLInputElement> for inputs, React.FormEvent<HTMLFormElement> for forms, React.MouseEvent<HTMLButtonElement> for clicks.

Context null-default pattern: createContext<T | null>(null) with a hook that throws when the provider is missing. The failure becomes a clear error at the call site instead of a later undefined access.

const Ctx = createContext<User | null>(null);
function useUser(): User {
  const u = useContext(Ctx);
  if (!u) throw new Error("useUser must be used within UserProvider");
  return u;
}

Interviewers probe: 'Why is .current nullable on useRef<HTMLDivElement>(null)?' The ref is null before mount and after unmount. A non-null type would be wrong for most of the component's lifetime.

The boundary: unknown, runtime validation, declaration files

Anything that enters the program from outside is untyped: network responses, localStorage, postMessage, URL parameters. JSON.parse returns any. Annotate the result as unknown and validate it:

const raw: unknown = JSON.parse(text);
// raw.name is an error: 'raw' is of type 'unknown'

A schema library such as Zod converts unknown into a typed value or throws:

const UserSchema = z.object({ id: z.string(), name: z.string() });
const user = UserSchema.parse(raw); // user: { id: string; name: string }

@types/* packages supply declarations for untyped JavaScript libraries. Module augmentation extends a module's existing types:

declare module "express-session" {
  interface SessionData { userId: string }
}

For an untyped dependency, write a .d.ts file with a declare module "lib" { ... } block, or wrap the library in a typed adapter. A bare declare module "lib"; gives every import implicit any, so use it only when you accept that loss.

Interviewers probe: 'Where does runtime validation go?' At every I/O boundary: API responses, form input, storage and URL parameters. Internal code that is already typed does not need it.

Compiler configuration and the build pipeline

The flags that change what gets caught:

  • strict enables strictNullChecks, strictFunctionTypes, strictBindCallApply, noImplicitAny, noImplicitThis, alwaysStrict and useUnknownInCatchVariables.
  • strictNullChecks makes null and undefined distinct from other types. It is the most valuable single flag.
  • noUncheckedIndexedAccess adds undefined to the type of arr[i] and obj[key], so unchecked access is flagged.
  • exactOptionalPropertyTypes separates { x?: string } from { x?: string | undefined }.
  • isolatedModules requires each file to be transpilable on its own, which swc, esbuild and Babel need.
  • verbatimModuleSyntax requires import type for type-only imports, so transpilers can remove them safely.
{
  "compilerOptions": {
    "strict": true,
    "noUncheckedIndexedAccess": true,
    "exactOptionalPropertyTypes": true,
    "isolatedModules": true,
    "verbatimModuleSyntax": true
  }
}

swc and esbuild transpile file by file and never resolve types across files. They strip syntax and report no type errors. tsc --noEmit is the type check. The bundler handles emit. Most pipelines run both.

Interviewers probe: 'Why does esbuild not catch type errors?' It has no whole-program type graph. Checking types requires that graph, which tsc builds.

Failure modes and what interviewers probe

  • any creep: one any spreads to every expression it touches, and checking stops silently there. Use unknown at boundaries.
  • Lying casts: data as User compiles regardless of shape. The mismatch appears at runtime, often in production.
  • Expensive types: recursive conditional or mapped types over large unions can slow tsc badly. tsc --generateTrace with --diagnostics shows which types dominate. Flatten the type or cap recursion.
  • Over-typing: types that mirror implementation details break on each refactor. Type the contract.

What interviewers probe most:

  • 'What does TypeScript not catch?' The runtime boundary.
  • 'Structural or nominal?' Structural, with excess property checks on literals.
  • 'Why is Array<T> unsound?' Covariance combined with mutation.
  • 'When satisfies instead of as?' When you want the check without losing literal types.
  • 'Where does validation live?' At I/O edges.

A weak answer stops at the definition, for example 'a union is a type that can be one of several.' A strong answer gives the trade-off, the failure mode and the runtime consequence. That difference is what separates a senior answer from a tutorial recital.

Feedback on this overview