Menu

Generic Types, Interfaces, and Classes

Lesson 2: Generic Types, Interfaces, and Classes

Where can type parameters go?

Construct Syntax Example use
Type alias type ApiResponse<T> = { data: T; ... } Wrap any API payload
Interface interface Page<T> { items: T[]; total: number } Paginated lists
Class class Repository<T> { ... } Store and fetch entities
Built-in types Array<T>, Promise<T>, Map<K, V>, Set<T> Everyday code

Example

type ApiResponse<T> = {
  data: T;
  status: number;
  fetchedAt: Date;
};

interface Page<T> {
  items: T[];
  page: number;
  pageSize: number;
  total: number;
}

type Product = { id: string; name: string; price: number };
type Order = { id: string; total: number };

const products: ApiResponse<Page<Product>> = {
  data: { items: [{ id: 'p1', name: 'Milk 1L', price: 6400 }], page: 1, pageSize: 20, total: 1 },
  status: 200,
  fetchedAt: new Date(),
};

class Repository<T extends { id: string }> {
  private items = new Map<string, T>();

  save(item: T): void {
    this.items.set(item.id, item);
  }

  findById(id: string): T | undefined {
    return this.items.get(id);
  }

  all(): T[] {
    return [...this.items.values()];
  }
}

const productRepo = new Repository<Product>();
productRepo.save({ id: 'p1', name: 'Milk 1L', price: 6400 });
const found = productRepo.findById('p1'); // Product | undefined

const orderRepo = new Repository<Order>();

How it works

  • Generic types are like functions for types: Page<Product> fills T with Product.
  • Generic types can be nested: ApiResponse<Page<Product>>.
  • One Repository class now serves products, orders, and customers with full type safety.
  • T extends { id: string } is a constraint (Lesson 3): only types with an id are allowed.

Common mistakes

Mistake Effect Fix
Writing ProductResponse, OrderResponse, CustomerResponse by hand Duplicated shapes drift apart Use one ApiResponse<T>
Forgetting the type argument on an empty generic class T becomes unknown Write new Repository<Product>()
Creating generic types with five or more parameters Hard to use and read Split into smaller types

Key takeaways

  • Generic types and classes model reusable containers: responses, pages, repositories.
  • Built-in types like Promise<T> and Map<K, V> are generics you already use.

Try it: Create a generic Cache<T> class with get, set, and an expiry time per entry, then use it for products and delivery slots.


TypeScript Tutorial

J

Jebasta





Get in Touch For Details