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.
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.
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.
// 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 | undefinedTypeScript 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.
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 lengthQ3. Explain keyof, typeof and indexed access types#
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 Usertypeof(in a type position) gets the type of a value.keyofproduces 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?#
| Utility | What it does | Example use |
|---|---|---|
Partial<T> | All properties optional | Update/patch payloads |
Required<T> | All properties required | Config after defaults applied |
Readonly<T> | All properties readonly | Immutable state |
Pick<T, K> | Keep only keys K | Card showing a few fields |
Omit<T, K> | Remove keys K | Create form without id |
Record<K, V> | Object with keys K and values V | Lookup maps |
ReturnType<F> | Return type of a function | Typing a selector's result |
Awaited<T> | Unwrap a Promise | Result of an async function |
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.
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#
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.
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.
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>>; // numberNarrowing 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.
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.
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?#
| Type | Meaning | Can you use it directly? |
|---|---|---|
any | Turns off type checking | Yes, anything goes (unsafe) |
unknown | Could be anything; must be checked | No, narrow it first |
never | A value that can't exist | Used for impossible branches and functions that throw |
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
}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.
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 existWith 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#
| Concept | Syntax |
|---|---|
| Generic with constraint | <T extends X> |
| Keys of a type | keyof T |
| Property type | T[K] |
| Mapped type | { [K in keyof T]: ... } |
| Conditional type | T extends U ? X : Y |
| Capture a type | infer R |
| Type guard | (x): x is T |
| Exhaustive check | const n: never = value |
Key takeaways#
- Generics keep the link between input and output types; constraints with
extendsmake them safe to use. keyof,typeofandT[K]combine into type-safe property access.- Utility types like
Partial,PickandOmitare mapped and conditional types you can write yourself. inferextracts parts of types; conditional types distribute over unions.- Use discriminated unions with a
nevercheck, and preferunknownoveranyfor untrusted data.