Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 77 ยท Web and Frontend Interview Questions

TypeScript Interview Questions

Prepare for TypeScript interviews: structural typing, generics, unknown versus any, type narrowing and utility types, with read-only types and runnable stand-ins.

TypeScript interviews check one thing above all: do you understand that types are a compile-time layer on top of JavaScript? Almost every good answer comes back to that. Types are erased before the code runs, so they cannot validate data that arrives at runtime, and they only describe the shape of values, not their names or classes.

This lesson walks through the questions that come up most: structural typing, generics, unknown versus any, narrowing, and the utility types. Type-level code is shown in read-only blocks, because the point is what the compiler says. Where it helps, a ```js stand-in shows the runtime behavior the types model, and one example runs through the real TypeScript compiler on the site's runner. See the TypeScript tutorial for the full story.

Types exist only at compile time

Shape, not name Structural typing.
Generics One function, many types.
Narrowing Prove the type with checks.
Utility types Transform types, not values.

After compiling, none of it remains in the JavaScript.

1 / 2

What is structural typing?

Short answer: TypeScript compares types by their shape. If a value has all the properties the target type needs, with compatible types, it is assignable, regardless of what it is called or which interface it "implements". Java and C# use nominal typing, where names matter.

TypeScript
interface Point {
  x: number;
  y: number;
}

function length(p: Point): number {
  return Math.hypot(p.x, p.y);
}

const pixel = { x: 3, y: 4, color: "red" };
length(pixel);                      // OK: it has x and y (extra properties are fine here)
length({ x: 3, y: 4, color: "red" }); // Error: object literal may only specify known properties

The last line surprises people. Excess property checking only applies to fresh object literals written directly at the call, to catch typos. The variable pixel is not fresh, so it passes. A good answer mentions both.

The runtime equivalent is duck typing: "if it has the methods I need, I can use it". This stand-in checks a shape the way the compiler conceptually does:

JS Stand-in: shape compatibility

Press Run (or Ctrl + Enter) to see the console output here.

No output.

interface versus type

Both describe object shapes and are largely interchangeable. The differences that matter:

  • interface supports declaration merging: declaring the same name twice combines them (used to augment library types). type aliases cannot be reopened.
  • type can name unions, intersections, tuples, primitives and mapped or conditional types. interface cannot be a union.
  • Both can be extended: interface B extends A, or type B = A & { extra: string }.

A safe rule to state: use interface for public object contracts that others may extend, and type for everything else, and stay consistent within a codebase.

any, unknown and never

  • any turns off checking. You can do anything with it, and it spreads: a value derived from any is usually any as well.
  • unknown is the type-safe "I don't know yet". You can assign anything to it, but you cannot use it until you narrow it.
  • never is the type with no values: the return type of a function that always throws, and what remains when a union has been fully narrowed.
TypeScript
function parseLoose(json: string): any {
  return JSON.parse(json);
}
const a = parseLoose('{"n": 1}');
a.nope.deeper;                   // compiles; crashes at runtime

function parseSafe(json: string): unknown {
  return JSON.parse(json);
}
const u = parseSafe('{"n": 1}');
u.n;                             // Error: 'u' is of type 'unknown'
if (typeof u === "object" && u !== null && "n" in u) {
  console.log(u.n);              // OK after narrowing (n is unknown here)
}

Prefer unknown for data you do not control (parsed JSON, catch variables, API responses) and validate it. A strong follow-up answer: because types are erased, validating an API response needs a runtime check (hand-written, or a validation library); a type annotation alone proves nothing.

Narrowing

Narrowing means the compiler refines a type inside a branch, based on checks it understands: typeof, instanceof, in, equality, truthiness, and user-defined type guards (function isString(x: unknown): x is string). The most useful pattern is the discriminated union: every member has a literal-typed tag, and a switch on the tag narrows to one member. Add a never check to make the compiler tell you when a new member is not handled.

This example runs through the real TypeScript compiler (type-checked with --strict, then executed):

TypeScript Discriminated union with an exhaustiveness check

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Try adding a fourth member { kind: "triangle"; base: number; height: number } to Shape without a new case. The compiler stops with an error on the assertNever(shape) line, because shape is no longer never. That is exactly the safety net interviewers want you to describe.

Generics

A generic is a type parameter: it lets one function or type work for many types while keeping the relationship between input and output. identity<T>(x: T): T returns exactly the type it gets, whereas identity(x: any): any loses it.

TypeScript
function first<T>(items: T[]): T | undefined {
  return items[0];
}
const n = first([1, 2, 3]);       // number | undefined
const s = first(["a", "b"]);      // string | undefined

// Constraints: T must have a length
function longest<T extends { length: number }>(a: T, b: T): T {
  return a.length >= b.length ? a : b;
}
longest("apple", "fig");          // string
longest([1, 2], [3]);             // number[]
longest(10, 20);                  // Error: number has no length

// keyof: a safe property getter
function getProp<T, K extends keyof T>(obj: T, key: K): T[K] {
  return obj[key];
}

The classic question is "when do you not need a generic?" If the type parameter appears only once in the signature, it does not relate anything to anything else, and a plain type is simpler.

At runtime a generic function is just a function; the type parameter vanishes. This stand-in shows the property-getter idea with a runtime guard for what the compiler checks statically:

JS Stand-in: what keyof checks at compile time

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Utility types

Utility types transform an existing type, so you do not repeat yourself. Know these by heart:

Utility What it gives you
Partial<T> every property optional
Required<T> every property required
Readonly<T> every property read-only
Pick<T, K> only the listed keys
Omit<T, K> everything except the listed keys
Record<K, V> an object type with keys K and values V
ReturnType<F> what a function returns
Awaited<T> the value inside a Promise
NonNullable<T> T without null and undefined
TypeScript
interface User {
  id: number;
  name: string;
  email: string;
}

type UserPreview = Pick<User, "id" | "name">;
type NewUser = Omit<User, "id">;
type UserPatch = Partial<NewUser>;       // for PATCH requests
type UsersById = Record<number, User>;

Interviewers sometimes ask you to implement one. Partial is a mapped type:

TypeScript
type MyPartial<T> = { [K in keyof T]?: T[K] };
type MyPick<T, K extends keyof T> = { [P in K]: T[P] };

The runtime stand-in below does the same transformation on values, which is a good way to remember what each utility means:

JS Stand-in: Pick and Omit as functions on values

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Honesty check: the ```js blocks above are models of the type-level ideas. They do not show how the compiler works internally. They show the idea each type expresses about your values.

Other frequent questions

  • enum versus a union of string literals? Enums emit runtime code; a union like "asc" | "desc" is erased and often simpler.
  • as assertions versus type guards? as tells the compiler to trust you and checks nothing. A guard actually checks.
  • What does strict do? It turns on a family of checks, including strictNullChecks (no accidental undefined) and noImplicitAny.
  • readonly versus const? const stops reassigning a variable; readonly stops changing a property. Neither freezes the object at runtime (Object.freeze does).
  • Can TypeScript check my API data? Not by itself. Types are erased; validate at the boundary.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Two unrelated interfaces both have { id: number }. Can a value of one be passed where the other is expected?

    Assignability depends on shape. Matching names or declared relationships are not required.
  2. 2. What is the main difference between unknown and any?

    unknown forces you to prove what a value is before you use it, while any silently disables the checks.
  3. 3. What is the point of an assertNever(shape) call in the default branch of a switch over a discriminated union?

    After all cases are handled, shape is never. Adding a member leaves a non-never type there and compilation fails.
  4. 4. A function is declared function f<T>(x: string): void. What is wrong with it?

    A type parameter should connect at least two places (input to output, or one input to another). A lone unused one is noise.
  5. 5. Why does JSON.parse(text) as User not make your program safe?

    The assertion only changes what the compiler believes. The actual data can be anything, so validate it at runtime.

Summary

  • TypeScript is structurally typed: shape decides assignability, and excess property checks apply only to fresh object literals.
  • Types are erased at compile time, so external data needs runtime validation.
  • Prefer unknown over any, then narrow with typeof, in, instanceof, guards or discriminated unions.
  • Use assertNever to make unions exhaustive.
  • Generics keep relationships between types; constrain them with extends and keyof.
  • Utility types (Partial, Pick, Omit, Record, ReturnType, Awaited) transform types without repetition.

Next: SQL: Query-Writing Interview Questions.