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:
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:
interface HasLength {
length: number;function logLength
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
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 free Pairlet interview room](https://www.pairlet.dev/interview/new) 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'.
Conduct Live Coding Interviews with Zero Friction
No candidate sign-up required. Create an instant room, share the link, and code together in real time with shared code execution.