说明

当定义一些类的时候,也可以使用泛型进行约束。

使用

先来创建一个类:

  1. class Collection {
  2. data: number[] = [];
  3. public push(...items: number[]) {
  4. this.data.push(...items);
  5. }
  6. public shift(): number {
  7. return this.data.shift() as number; // 出现了一个问题 返回值可能是T | undefined 所以加上一个类型断言
  8. }
  9. }

上面的代码中创建了一个类,在这个类中通过push方法向数组中插入数字,shift方法从数组中抽取数据。

该类的缺陷也很明显,仅仅只能传递数字类型,如果想要传递其他类型,就需要使用到泛型,修改之后的代码如下:

    class CollectionNumber <T>{
        data: T[] = [];
        public push(...items: T[]) {
            this.data.push(...items);
        }

        public shift(): T {
            return this.data.shift() as T; // 出现了一个问题 返回值可能是T | undefined 所以加上一个类型断言
        }
    }

将泛型引入之后,这个类在使用的时候,就可以传递任何的想传递的类型。

const numberCollection = new Collection();
numberCollection.push(1, 2, 3, 4, 5);

console.log(numberCollection.shift());
console.log(numberCollection.shift());

const stringCollection = new Collection();
stringCollection.push('aa', 'bb', 'cc', 'dd');

console.log(stringCollection.shift());
console.log(stringCollection.shift());
console.log(stringCollection.shift());