编辑
2023-03-25
TypeScript
0
请注意,本文编写于 532 天前,最后修改于 515 天前,其中某些信息可能已经过时。

目录

泛型基础相关
泛型的概念
语法
泛型函数
说明
单个参数泛型函数
多个参数泛型函数
泛型参数默认类型
泛型接口
泛型函数的类型
常规的写法
调用签名的对象字面量
演化为接口方式
在此基础上将泛型参数\<T>提前到接口上
注意点
泛型类
说明
Eg
泛型约束
说明
Eg
在泛型约束中使用类型参数
泛型的优点

泛型基础相关

泛型的概念

泛型指在定义函数、接口或者类时,未指定其参数类型,只有在运行时传入才能确定;
此时参数类型作为变量采用字母T表示,也可以采用其它字母表示

语法

在函数名、接口名或类名后添加<T>;

泛型函数

说明

使用泛型后,参数类型和返回值类型都可以使用T表示 泛型函数的返回值类型是根据需求决定,可以指定返回值类型 多个参数泛型函数语法为通过逗号分隔 <T, U, K>

单个参数泛型函数

ts
function myTest<T>(x: T): T { return x } let a = myTest(14) let b = myTest("str") console.log(a, typeof a) // 14 number console.log(b, typeof b) // str string //也可根据需求指定返回值类型 function myTest<T>(x: T): string { return String(x) } let a = myTest(14) console.log(a, typeof a) // 14 string

多个参数泛型函数

ts
function myTest<T, U>(x: T, y: U): T & U { return x as T & U } let a = myTest("14", 2) console.log(a, typeof a)

泛型参数默认类型

泛型函数参数可以定义默认类型,通过<T = defaultType>

ts
function myTest<T = string>(x: T): T { return x } let a = myTest(14) let b = myTest("str") console.log(a, typeof a)//14 number console.log(b, typeof b)//str string

泛型接口

泛型函数的类型

常规的写法

ts
function test<T>(x: T): T { return x } let myTest: <T>(x: T) => T = test

调用签名的对象字面量

通过带有调用签名的对象字面量的方式来定义泛型函数

ts
function test<T>(x: T): T { return x } let myTest:{<T>(x:T):T}= test

演化为接口方式

ts
interface testInt { <T>(x: T): T } function test<T>(x: T): T { return x } let myTest: testInt = test

在此基础上将泛型参数<T>提前到接口上

ts
interface testInt<T> { (x: T): T } function test<T>(x: T): T { return x } let myTest: testInt = test

注意点

在使用泛型接口时,需要传入一个类型参数来指定泛型类型,锁定之后代码里使用的类型

ts
interface testInt<T> { (x: T): T } function test<T>(x: T): T { return x } let myTest: testInt<string> = test

泛型类

说明

泛型类使用<>括起泛型类型,跟在类名后面 静态属性不能使用泛型类

泛型类

Eg

ts
class myTest<T> { add!: (x: T, y: T) => T } let a = new myTest<number>() a.add = (x, y) => {return x + y} let b = a.add(1, 2) console.log(b) // 3

泛型约束

说明

定义一个接口描述约束条件,使用这个接口和extends关键字实现约束

Eg

ts
//泛型约束 // 定义一个接口描述约束条件 interface usersName { name: string } function myTest<T extends usersName>(names:T):T { console.log(names.name) // li return names } let a = myTest({name:"li"}) console.log(a,typeof a) // { name: 'li' } object

<T extends usersName>约束了T类型必须是userName的子类型

在泛型约束中使用类型参数

keyof T: 用于获取T对象的所有键名

ts
// 在泛型约束中使用类型参数 function myTest<T, K extends keyof T>(x: T, y: K) { return x[y] } let a = { a: 1, b: 2, c: "3" } let result = myTest(a, "c") console.log(result)

泛型的优点

  1. 函数和类可以轻松的支持多种类型,增强程序的扩展性
  2. 不必写多条函数重载,冗长的联合类型声明,增强代码可读性
  3. 灵活控制类型之间的约束

本文作者:RKLS

本文链接:

版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!