EasyGenerics📖 Theory Question

What are generics and why are they useful in TypeScript?

💡

Hint

Type parameters that make functions/classes/interfaces reusable across multiple types while preserving type safety

Full Answer

Generics are type parameters that let you write reusable code that works with multiple types without sacrificing type safety.

// Without generics — must duplicate or use any
function getFirstAny(arr: any[]): any { return arr[0]; }

// With generics — type-safe and reusable
function getFirst<T>(arr: T[]): T { return arr[0]; }

const n = getFirst([1, 2, 3]);    // T inferred as number
const s = getFirst(['a', 'b']);   // T inferred as string
// n and s have correct types — no runtime casting needed

Generic interfaces and types:

interface ApiResponse<T> {
  data: T;
  status: number;
  message: string;
}

type UserResponse  = ApiResponse<User>;
type ListResponse  = ApiResponse<User[]>;

// Generic class
class Stack<T> {
  private items: T[] = [];
  push(item: T): void { this.items.push(item); }
  pop(): T | undefined { return this.items.pop(); }
  peek(): T | undefined { return this.items[this.items.length - 1]; }
}

const numStack = new Stack<number>();
numStack.push(1);
numStack.push('a'); // ❌ Error — string not assignable to number
💡 Think of generics as function parameters for types. Just as function parameters make a function reusable for different values, type parameters make types reusable for different types.

More Generics Questions

EasyWhat are generic constraints and how do you use the extends keyword with them?→EasyWhat are default type parameters in TypeScript generics?→EasyWhat is conditional generic typing — how do you write T extends U ? X : Y?→MediumHow do generic functions differ from generic types? Show examples of each.→

Practice this in a timed sprint →

5 free questions, no signup required

⚡ Start Sprint