QA
Intermediate LevelJavaScript & TypeScript

How do TypeScript generics work in functions, interfaces, and classes?

❓ Interview Prompt: Explain generic type parameters (<T>), generic constraints (extends), default generics, and multi-parameter generics.

Generics allow creating reusable components that work over a variety of types rather than a single fixed type, maintaining full static type safety.

Generic Patterns:

1
Generic Functions: function identity<T>(arg: T): T {}
2
Generic Interfaces: interface ApiResponse<Data> { data: Data; status: number; }
3
Generic Constraints: Restrict allowed generic types using extends: <T extends { length: number }>.

Code Implementation Example

typescript
// Generic Interface for API responses
interface ApiResponse<T> {
  data: T;
  status: number;
  error?: string;
}

// Generic function with constraint (T must have length property)
function logLength<T extends { length: number }>(item: T): number {
  console.log('Length is:', item.length);
  return item.length;
}

logLength('Hello');      // ✅ string has length
logLength([1, 2, 3]);    // ✅ Array has length
// logLength(42);        // ❌ Error: number doesn't have length!

// Generic Repository Class
class DataStore<T extends { id: string | number }> {
  private items: T[] = [];
  add(item: T) { this.items.push(item); }
  getById(id: string | number): T | undefined {
    return this.items.find(item => item.id === id);
  }
}
💡Generic ApiResponse interface, generic constraint with extends, and generic DataStore class.
🎯 Interview Key Takeaway

Generics capture and enforce relationships between parameters and return types without resorting to any.

#TypeScript#Generics#Constraints#Intermediate
Back to all JavaScript & TypeScript Questions→

More JavaScript & TypeScript Interview Questions

Beginner LevelJavaScript & TypeScript

What are the differences between var, let, and const in JavaScript?

Beginner LevelJavaScript & TypeScript

What are the JavaScript data types and the difference between primitives and objects?

Beginner LevelJavaScript & TypeScript

What is the difference between == (loose equality) and === (strict equality)?