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 stringGeneric Constraints (extends)
Restrict accepted type arguments using the extends keyword:
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
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 userTest TypeScript Skills Live
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 in the Browser
No candidate sign-up required. Create a room, share the link, and code together in real time with shared code execution.