TypeScript教程之七:泛型


由微软推出的TypeScript自从一推出就广受关注,现在无论开发前端React/Vue,还是后端API,很多项目中都广泛接受了TypeScript。下面介绍TS中的泛型。

TypeScript

泛型概念

泛型的主要作用就是针对不同数据类型,定义相同的处理逻辑。也就是说,在定义函数或者变量类型的时候,又多了一个变量,就是变量自己的类型。可以在函数参数,函数返回值,类方法,类的实例成员上应用泛型。

针对基本类型使用泛型

function concat<T>(a: T, b: T) {
    return `${a}${b}`;
}

concat<string>("abc", "def");
concat<number>(3, 5);

在数组中使用泛型

function f1<T>(params: T[]) {
    return params.length;
}

console.log(f1<number>([1,3,5]));

再举一个例子:

function reverse<T>(items: T[]): T[] {
  const reversed = [];
  for (let i = items.length - 1; i >= 0; i--) {
    reversed.push(items[i]);
  }
  return reversed;
}

const a1 = [1, 3, 5];
console.log(reverse<number>(a1));
// 或者可以使用类型推断: console.log(reverse(a1));

const a2 = ['Hello', 'TS'];
console.log(reverse<string>(a2));

在类中使用泛型

interface Animal {
    eat(): void;
}

class Dog implements Animal {
    eat() {
        console.log("I eat bones.")
    }
}

class AnimalHelper<T extends Animal> {
    intro(animal: T) {
        animal.eat();
        // other methods ...
    }
}

const d = new Dog();
const ah = new AnimalHelper();
ah.intro(d);

泛型举例:为对象添加一个随机ID

下面通过泛型来实现一个方法,为传递过来的对象添加一个id属性,其值为一个随机的ID。例子中只使用random来作为演示,实际项目中肯定要使用类似uuid这样的库来实现真正的唯一性ID。

function addID<T extends {name: string}>(o: T) {
    return {...o, id: Math.floor(Math.random() * 1000)}
}

const paul = {name: 'Paul', address: '1 Fake St'};
const newObj = addID(paul);
console.log(newObj);

文章作者: 逻思
版权声明: 本博客所有文章除特別声明外,均采用 CC BY-NC-ND 4.0 许可协议。转载请注明来源 逻思 !
  目录