Skip to main content
1:1 mock interviews with Sumit, scored on a real hiring rubric.Book a slot →

Advanced TypeScript Interview Questions: Generics, Utility, Mapped and Conditional Types

12 advanced TypeScript interview questions with code: generics and constraints, keyof and typeof, utility types, mapped types, conditional types, infer, type guards, discriminated unions, never, unknown vs any, and template literal types.

Sumit KumarUpdated Oct 12, 20267 min readTypeScript
Advanced TypeScript Interview Questions: Generics, Utility, Mapped and Conditional Types

Once you know basic TypeScript annotations, interviews move on to the type system itself: generics, utility types, and types that compute other types. This post covers 12 advanced TypeScript questions that come up for fresher-to-mid frontend roles, each with a short answer, code and an explanation.

Map of advanced TypeScript types: utility types like Partial and Pick, mapped types, conditional types with infer, and type narrowing with guards

For the basics (interfaces vs types, enums, tsconfig) see TypeScript interview questions first.

Generics and operators#

Q1. What are generics and why use them?#

Answer: generics are type parameters. They let a function, class or type work with many types while keeping the relationship between input and output types.

TypeScript
// Without generics: the return type is lost
function firstAny(arr: any[]): any { return arr[0]; }

// With generics: the type flows through
function first<T>(arr: T[]): T | undefined {
  return arr[0];
}

const n = first([1, 2, 3]);      // number | undefined
const s = first(["a", "b"]);     // string | undefined

TypeScript usually infers T from the arguments, so you rarely write first<number>(...).

Q2. What is a generic constraint?#

Answer: extends limits what a type parameter can be, so you can safely use its properties.

TypeScript
function longest<T extends { length: number }>(a: T, b: T): T {
  return a.length >= b.length ? a : b;
}

longest("hello", "hi");      // OK: strings have length
longest([1, 2], [1, 2, 3]);  // OK: arrays have length
longest(10, 20);             // Error: number has no length

Q3. Explain keyof, typeof and indexed access types#

TypeScript
const user = { id: 1, name: "Asha", active: true };

type User = typeof user;          // { id: number; name: string; active: boolean }
type UserKey = keyof User;        // "id" | "name" | "active"
type NameType = User["name"];     // string

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

getProp(user, "name");   // string
getProp(user, "email");  // Error: "email" is not a key of User
  • typeof (in a type position) gets the type of a value.
  • keyof produces a union of an object type's keys.
  • T[K] looks up the type of a property.

The getProp pattern is a favourite interview question because it combines all three.

Utility and mapped types#

Q4. Which built-in utility types do you use most?#

UtilityWhat it doesExample use
Partial<T>All properties optionalUpdate/patch payloads
Required<T>All properties requiredConfig after defaults applied
Readonly<T>All properties readonlyImmutable state
Pick<T, K>Keep only keys KCard showing a few fields
Omit<T, K>Remove keys KCreate form without id
Record<K, V>Object with keys K and values VLookup maps
ReturnType<F>Return type of a functionTyping a selector's result
Awaited<T>Unwrap a PromiseResult of an async function
TypeScript
interface Todo { id: number; title: string; done: boolean }

type TodoPreview = Pick<Todo, "id" | "title">;
type NewTodo = Omit<Todo, "id">;
function updateTodo(id: number, changes: Partial<Todo>) { /* ... */ }

Q5. What is a mapped type? Implement Partial and Readonly yourself#

Answer: a mapped type loops over the keys of another type and transforms each property.

TypeScript
type MyPartial<T> = { [K in keyof T]?: T[K] };
type MyReadonly<T> = { readonly [K in keyof T]: T[K] };

// Remove modifiers with "-"
type Mutable<T> = { -readonly [K in keyof T]: T[K] };

// Remap keys with "as" (key remapping)
type Getters<T> = {
  [K in keyof T as `get${Capitalize<string & K>}`]: () => T[K];
};
type UserGetters = Getters<{ name: string; age: number }>;
// { getName: () => string; getAge: () => number }

Q6. Implement Pick and Omit#

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

type MyOmit<T, K extends keyof any> = Pick<T, Exclude<keyof T, K>>;

Explanation: Pick maps over only the chosen keys. Omit uses Exclude to remove keys from keyof T, then picks the rest. Interviewers like this question because it shows you can build types from smaller types.

Conditional types#

Q7. What are conditional types?#

Answer: a conditional type chooses between two types based on whether one type is assignable to another: T extends U ? X : Y.

TypeScript
type IsString<T> = T extends string ? "yes" : "no";
type A = IsString<"hi">;   // "yes"
type B = IsString<42>;     // "no"

// Distributive over unions:
type MyExclude<T, U> = T extends U ? never : T;
type C = MyExclude<"a" | "b" | "c", "a">; // "b" | "c"

type MyNonNullable<T> = T extends null | undefined ? never : T;

When T is a union, the condition is applied to each member separately (distributive conditional types). That's how Exclude filters a union.

Q8. What does the infer keyword do?#

Answer: infer declares a type variable inside a conditional type and lets TypeScript capture part of a type.

TypeScript
type MyReturnType<F> = F extends (...args: any[]) => infer R ? R : never;
type ElementType<T> = T extends (infer E)[] ? E : T;
type UnwrapPromise<T> = T extends Promise<infer V> ? V : T;

type R1 = MyReturnType<() => boolean>;   // boolean
type R2 = ElementType<string[]>;         // string
type R3 = UnwrapPromise<Promise<number>>; // number

Narrowing and safety#

Q9. How does type narrowing work? What is a custom type guard?#

Answer: TypeScript narrows a union inside a branch based on checks like typeof, instanceof, in and equality. A custom type guard is a function returning value is Type.

TypeScript
function format(input: string | number | Date) {
  if (typeof input === "string") return input.toUpperCase();
  if (typeof input === "number") return input.toFixed(2);
  return input.toISOString();   // narrowed to Date
}

interface Cat { meow(): void }
interface Dog { bark(): void }

function isCat(pet: Cat | Dog): pet is Cat {
  return "meow" in pet;
}

function speak(pet: Cat | Dog) {
  if (isCat(pet)) pet.meow();  // Cat
  else pet.bark();             // Dog
}

Q10. What is a discriminated union? How do you make a switch exhaustive?#

Answer: a discriminated union is a union of object types that share a literal property (the discriminant), such as status or type. Checking it narrows to one member. Assigning the leftover value to never makes the compiler flag any unhandled case.

TypeScript
type RequestState =
  | { status: "loading" }
  | { status: "success"; data: string[] }
  | { status: "error"; message: string };

function render(state: RequestState) {
  switch (state.status) {
    case "loading": return "Loading...";
    case "success": return state.data.join(", ");
    case "error":   return "Error: " + state.message;
    default: {
      const unreachable: never = state; // error if a case is missing
      return unreachable;
    }
  }
}

This pattern is common for reducer actions and API states in React apps.

Q11. What is the difference between any, unknown and never?#

TypeMeaningCan you use it directly?
anyTurns off type checkingYes, anything goes (unsafe)
unknownCould be anything; must be checkedNo, narrow it first
neverA value that can't existUsed for impossible branches and functions that throw
TypeScript
function parse(json: string): unknown {
  return JSON.parse(json);
}
const value = parse('{"a":1}');
value.a;                       // Error: value is unknown
if (typeof value === "object" && value !== null && "a" in value) {
  console.log(value.a);        // OK after narrowing
}
Interview tip

Prefer unknown for external data (API responses, JSON.parse, catch errors) and validate it, for example with a schema library like Zod.

Q12. What are template literal types and the satisfies operator?#

Answer: template literal types build string types from other types. satisfies checks that a value matches a type without widening the value's inferred type.

TypeScript
type Size = "sm" | "md" | "lg";
type Color = "red" | "blue";
type ClassName = `btn-${Size}-${Color}`;  // "btn-sm-red" | "btn-sm-blue" | ...

type EventName<T extends string> = `on${Capitalize<T>}`;
type ClickHandler = EventName<"click">;    // "onClick"

const routes = {
  home: "/",
  profile: "/profile",
} satisfies Record<string, string>;

routes.home;    // type is still the literal-preserving object
routes.about;   // Error: property doesn't exist

With a plain annotation (const routes: Record<string, string>), routes.about would be allowed, because every string key is valid. satisfies gives you both the check and the precise type.

Quick revision#

ConceptSyntax
Generic with constraint<T extends X>
Keys of a typekeyof T
Property typeT[K]
Mapped type{ [K in keyof T]: ... }
Conditional typeT extends U ? X : Y
Capture a typeinfer R
Type guard(x): x is T
Exhaustive checkconst n: never = value

Key takeaways#

  • Generics keep the link between input and output types; constraints with extends make them safe to use.
  • keyof, typeof and T[K] combine into type-safe property access.
  • Utility types like Partial, Pick and Omit are mapped and conditional types you can write yourself.
  • infer extracts parts of types; conditional types distribute over unions.
  • Use discriminated unions with a never check, and prefer unknown over any for untrusted data.