BugCast
TS TypeScript

TypeScript Generics for Interviews

Write generic functions, constraints, and utility types confidently in interviews.

BugCast Admin··8 min read

Why Generics?

Write reusable code that works with multiple types while keeping type safety.

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

identity<string>("hello");
identity(42); // inferred as number

Constraints

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

Common Utility Types

type Partial<T> = { [K in keyof T]?: T[K] };
type Pick<T, K extends keyof T> = { [P in K]: T[P] };
type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;
type Record<K extends string, V> = { [P in K]: V };

Interview Questions

Q: Implement a typed Array.prototype.first

function first<T>(arr: T[]): T | undefined {
  return arr[0];
}

Q: What is infer?

Extract types inside conditional types:

type ReturnType<T> = T extends (...args: any[]) => infer R ? R : never;

Q: Generic vs any?

Generics preserve type information through the call chain. any disables checking entirely.

#generics#typescript#interview

Related posts