Giải thích các generics trong TypeScript?

{{FormatNumbertoThousand(model.total_like)}} lượt thích
930 lượt xem

Generics có thể tạo một component hoặc function để hoạt động trên nhiều kiểu thay vì một kiểu duy nhất.

/** A class definition with a generic parameter */
class Queue<T> {
   private data = [];
   push = (item: T) => this.data.push(item);
   pop = (): T => this.data.shift();
} 

const queue = new Queue<number>();
queue.push(0);
queue.push("1"); // ERROR : cannot push a string. Only numbers allowed
{{login.error}}