# 泛型

# hello world

  • 类型变量,只用于表示类型而不是值

  • 使返回值的类型和传入的参数类型是相同的

  • 类似 any ,但 any 无法保证传入的类型和返回的类型一致

function identity<T>(arg: T): T {
  return arg;
}
1
2
3

# 使用泛型变量

  • 如果在函数体内操作参数length属性,但入参并没有该属性,有可能会报错
function identity<T>(arg: T): T {
  console.log(arg.length) // Error: T doesn't have .length
  return arg;
}

function loggingIdentity<T>(arg: T[]): T[] {
  console.log(arg.length);
  return arg;
}
1
2
3
4
5
6
7
8
9

# 泛型类型

// 泛型函数
const myIdntity1: <T>(arg: T) => T = identity;
// 带有调用签名的对象字面量来定义
const myIdntity2: {<T>(arg: T): T} = identity;

// 泛型接口
interface GenIdentityFn {
  <T>(arg: T): T
}
const myIdntity3: GenIdentityFn = identity;

// 泛型参数当做接口的参数
interface GenIdentityFn2<T> {
  (arg: T): T
}
const myIdntity4: GenIdentityFn2<number> = identity;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

# 泛型类

// 泛型类
class GenericsClass1<T> {
  val: T;
  add: (x: T, y: T) => T;
}
const myGenClass1 = new GenericsClass1<number>();
myGenClass1.val = 12;

const myGenClass2 = new GenericsClass1<string>();
myGenClass2.val = '12';
1
2
3
4
5
6
7
8
9
10

# 泛型约束

interface Lengthwise {
  length: number
}
function loggingIdentity2<T extends Lengthwise>(arg: T): T {
  console.log(arg.length);
  return arg;
}

// const res = loggingIdentity2(12) // 类型“number”的参数不能赋给类型“Lengthwise[]”的参数。ts(2345)
const res = loggingIdentity2('hello')
const res2 = loggingIdentity2({ length: 12, name: 'hello'})
1
2
3
4
5
6
7
8
9
10
11