TypeScript1 min read

TypeScript Generics: Interview Questions and Practical Examples

Master TypeScript generics for technical interviews. Learn generic constraints, keyof lookups, inference, conditional types, and common generic utility implementations.

Pairlet Team•Published: •Updated:

Generics provide the foundation for reusable type-safe libraries in TypeScript. Interview questions often evaluate whether candidates can write parameterized functions, enforce constraints using extends, and infer return types dynamically.

What Are Generics?

Generics enable functions, interfaces, and classes to accept type parameters:

TYPESCRIPT
function identity<T>(arg: T): T {
  return arg;
}

const num = identity(42);       // Inferred as number
const str = identity("hello");  // Inferred as string

Generic Constraints (extends)

Restrict accepted type arguments using the extends keyword:

TYPESCRIPT
interface HasLength {
  length: number;
}

function logLength<T extends HasLength>(item: T): number {
  console.log(item.length);
  return item.length;
}

logLength("hello"); // OK (strings have .length)
logLength([1, 2, 3]); // OK (arrays have .length)
// logLength(123); // Error: Argument of type 'number' is not assignable to 'HasLength'

Combining Generics with keyof

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

const user = { id: 1, name: "Alice", active: true };
const name = getProperty(user, "name"); // Inferred as string
// const invalid = getProperty(user, "foo"); // Error: Argument of type '"foo"' is not assignable to keyof user

Test TypeScript Skills Live

Create a Pairlet interview room to practice live generic exercises with candidates.

Frequently Asked Questions

Why are generics essential in TypeScript?

Generics allow developers to create reusable, type-safe components and functions that work across multiple data types while preserving full compile-time type information without resorting to 'any'.

Practice Relevant Coding Problems
Practice Live Coding

Conduct Live Coding Interviews in the Browser

No candidate sign-up required. Create a room, share the link, and code together in real time with shared code execution.

Related Articles