← العودة إلى الدورة: TypeScript from scratch

Generic interfaces, aliases and classes

الفيديو قريبًا

Generics are not exclusive to functions. Interfaces, type aliases and classes can also receive type parameters. It is the way to build reusable structures: a box that stores anything, an API response with data of any shape, a stack or a queue. You will see patterns that repeat constantly in real projects, so it is worth mastering them with concrete examples.

Generic interfaces and aliases

A very typical case is an API response, which always has a status and some data, but the data changes depending on the endpoint. With a generic you describe the wrapper once: ApiResponse<T>. When using it you must give the concrete type between angle brackets, and the compiler substitutes T everywhere. You can give a default type with = so users do not always have to write it.

typescript
interface ApiResponse<T = unknown> {
  ok: boolean;
  data: T;
  error?: string;
}

interface User {
  id: number;
  name: string;
}

type Page<T> = {
  items: T[];
  total: number;
};

const userResponse: ApiResponse<User> = { ok: true, data: { id: 1, name: 'Ana' } };
const numbersPage: Page<number> = { items: [1, 2, 3], total: 3 };

console.log(userResponse.data.name.toUpperCase(), numbersPage.items.length);

Generic classes

In a class, the type parameter is declared after the name and is available in properties, constructor and methods. When creating an instance, you give the type with new Stack<number>() and from then on all the methods of that instance talk about number. A Stack<string> and a Stack<number> are incompatible types, which prevents mixing data by mistake. We have not studied classes in depth yet (that will be week 6), but this example uses only the minimum: properties, methods and the private modifier to hide the internal array.

typescript
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];
  }

  get size(): number {
    return this.items.length;
  }
}

const numbers = new Stack<number>();
numbers.push(1);
numbers.push(2);
// numbers.push('three'); // error: 'string' is not assignable to 'number'
console.log(numbers.pop(), numbers.size); // 2 1

Another useful pattern is the explicit result. Instead of throwing exceptions, a function returns a value that says whether it went well or badly, with a generic for the successful data. It is a type you will see again with discriminated unions in week 7: type Result<T> = { ok: true; value: T } | { ok: false; error: string }.

Notice there is no magic in any of these examples: the generic type is a template and the compiler generates a concrete version every time you use it. Stack<number> and Stack<string> share the same JavaScript code at runtime, because types are erased, but for the compiler they are different types. This explains why you cannot write new T() or use typeof T inside a generic: T does not exist at runtime. If you need to create instances, receive a factory function as a parameter and the problem disappears.

✎ ملاحظاتي

محفوظ في هذا المتصفح فقط. سجّل الدخول لحفظه في حسابك.0/5000 حرف

← السابقالتالي →