1. 泛型定义

在定义函数、接口、类的时候不能预先确定要使用的数据类型,而是在使用函数、接口、类的时候才能确定数据的类型。

泛型设计的目的是使在成员之间提供有意义的约束,为代码增加抽象层和提升可重用性。

2. 简单示例

需求1:定义一个函数,接收两个参数,第一个参数是数据类型,第二个参数是数量,函数的作用是根据数量产生对应个数的数据,存放在一个数组中并返回。

  1. function getArr1(value: number, count: number): number[] {
  2. const arr: number[] = []
  3. for(const i = 0; i < count; i++) {
  4. arr.push(value)
  5. }
  6. return arr
  7. }
  8. const arr = getArr1(111.11, 3)
  9. console.log(arr) // [111.11, 111.11, 111.11]

需求2:需要将getArr1函数接收的第一个参数改为字符串类型,并返回存储字符串类型的数组。

getArr1函数不能适用需求2,只能fork一下进行修改。

  1. function getArr2(value: string, count: number): string[] {
  2. const arr: string[] = []
  3. for(const i = 0; i < count; i++) {
  4. arr.push(value)
  5. }
  6. return arr
  7. }
  8. const arr = getArr2('abc', 3)
  9. console.log(arr) // ['abc', 'abc', 'abc']

需求3:如果要支持多种类型的话,按照上述写法就得写多种函数,显然这种方式不是很灵活。所以需要定义一个函数,第一个参数支持传入任意类型的数据,并返回存储这个任意类型数据的数组。

  1. function getArr3(value: any, count: number): any[] {
  2. const arr: any[] = []
  3. for(const i = 0; i < count; i++) {
  4. arr.push(value)
  5. }
  6. return arr
  7. }
  8. const arr1 = getArr3('abc', 3)
  9. const arr2 = getArr3(111.11, 3)
  10. console.log(arr1) // ['abc', 'abc', 'abc']
  11. console.log(arr2) // [111.11, 111.11, 111.11]

将数据类型定义成any类型的确能满足需求3,但是这样会有两点弊端:

  1. 上述结果中,arr1中存储的是数字类型的数据,arr2中存储的是字符串类型的数据,而我们通过arr1[0]调用数据的方法,以及通过arr[1]调用字符串的方法,都不会有任何的智能提示(要么有方法名字的提示信息,要么有错误的提示信息),这也是我们在写ts不希望看到的。

  2. 通过any类型,无法约束传入的类型与返回的类型是相同的。

需求4:定义一个函数,调用者可以在调用的时候明确传入的类型与返回的类型。这个时候就得使用泛型定义。

  1. function getArr4<T>(value: T, count: number): T[] {
  2. const arr: T[] = []
  3. // 或者 const arr: Array<T> = []
  4. for(const i = 0; i < count; i++) {
  5. arr.push(value)
  6. }
  7. return arr
  8. }
  9. const arr1 = getArr4<string>('abc', 3)
  10. const arr2 = getArr4<number>(111.11, 3)
  11. console.log(arr1) // ['abc', 'abc', 'abc']
  12. console.log(arr2) // [111.11, 111.11, 111.11]

3. 多个类型参数

定义泛型的时候,可以一次定义多个类型参数:

  1. function swap<T, U>(tuple: [T, U]): [U, T] {
  2. return [tuple[1], tuple[0]]
  3. }
  4. swap([7, 'seven']) // ['seven', 7]

4. 泛型约束

在函数内部使用泛型变量的时候,由于事先不知道它是哪种类型,所以不能随意的操作它的属性或方法:

  1. function loggingIdentity<T>(arg: T): T {
  2. console.log(arg.length);
  3. return arg;
  4. }
  5. // index.ts(2,19): error TS2339: Property 'length' does not exist on type 'T'.

上例中,泛型T不一定包含属性length,所以编译的时候报错了。

这时,我们可以对泛型进行约束,只允许这个函数传入那些包含length属性的变量。这就是泛型约束:

  1. interface Lengthwise {
  2. length: number
  3. }
  4. function loggingIdentity<T extends Lengthwise>(arg: T): T {
  5. console.log(arg.length)
  6. return arg
  7. }

上例中,我们使用了extends约束了泛型T必须符合接口Lengthwise的形状,也就是必须包含length属性。

此时如果调用loggingIdentity的时候,传入的arg不包含length,那么在编译阶段就会报错了:

  1. interface Lengthwise {
  2. length: number
  3. }
  4. function loggingIdentity<T extends Lengthwise>(arg: T): T {
  5. console.log(arg.length)
  6. return arg
  7. }
  8. loggingIdentity(7)
  9. // index.ts(10,17): error TS2345: Argument of type '7' is not assignable to parameter of type 'Lengthwise'.

多个类型参数之间也可以互相约束:

  1. function copyFields<T extends U, U>(target: T, source: U): T {
  2. for (let id in source) {
  3. target[id] = (<T>source)[id]
  4. }
  5. return target
  6. }
  7. let x = { a: 1, b: 2, c: 3, d: 4 }
  8. copyFields(x, { b: 10, d: 20 })

上例中,我们使用了两个类型参数,其中要求T继承U,这样就保证了U上不会出现T中不存在的字段。

5. 泛型接口

可以使用接口的方式来定义一个函数需要符合的形状:

  1. interface SearchFunc {
  2. (source: string, subString: string): boolean
  3. }
  4. let mySearch: SearchFunc
  5. mySearch = function(source: string, subString: string) {
  6. return source.search(subString) !== -1
  7. }

当然也可以使用含有泛型的接口来定义函数的形状:

  1. interface CreateArrayFunc {
  2. <T>(length: number, value: T): Array<T>
  3. }
  4. let createArray: CreateArrayFunc
  5. createArray = function<T>(length: number, value: T): Array<T> {
  6. let result: T[] = []
  7. for (let i = 0; i < length; i++) {
  8. result[i] = value
  9. }
  10. return result
  11. }
  12. createArray(3, 'x') // ['x', 'x', 'x']

进一步,我们可以把泛型参数提前到接口名上:

  1. interface CreateArrayFunc<T> {
  2. (length: number, value: T): Array<T>
  3. }
  4. let createArray: CreateArrayFunc<any>
  5. createArray = function<T>(length: number, value: T): Array<T> {
  6. let result: T[] = []
  7. for (let i = 0; i < length; i++) {
  8. result[i] = value
  9. }
  10. return result
  11. }
  12. createArray(3, 'x') // ['x', 'x', 'x']

注意,此时在使用泛型接口的时候,需要定义泛型的类型。

6. 泛型类

与泛型接口类似,泛型也可以用于类的类型定义中:

  1. class GenericNumber<T> {
  2. zeroValue: T
  3. add: (x: T, y: T) => T
  4. }
  5. let myGenericNumber = new GenericNumber<number>()
  6. myGenericNumber.zeroValue = 0
  7. myGenericNumber.add = function(x, y) { return x + y; }

7. 泛型参数的默认类型

我们可以为泛型中的类型参数指定默认类型。当使用泛型时没有在代码中直接指定类型参数,从实际值参数中也无法推测出时,这个默认类型就会起作用。

  1. function createArray<T = string>(length: number, value: T): Array<T> {
  2. let result: T[] = []
  3. for (let i = 0; i < length; i++) {
  4. result[i] = value
  5. }
  6. return result
  7. }