Skip to content

四、泛型

有时候,我们可能希望我们的类型定义⼀次,但是能够动态的⽣成其他的类型,这时就需要泛型支持了

一、泛型函数

typescript
function test<T>(arg: T): T { 
	return arg
} 
const str = test<string>('a') 
const num = test<number>(1)

二、泛型推断

⼤多数时候我们并不需要⼿动传 进去,它会⾃动推断

typescript
function test<T>(arg: T): T { 
	return arg 
} 
const str = test('a') // 推断为 string 
const num = test(1) // 推断为 number

三、泛型约束

有时候,我们可能需要限制泛型的范围,这时可以使⽤ extends 关键字

typescript
// 例如限制为数组类型 
function test><T extends Array<any>>(arg: T): T {
	return arg 
} 
const numberArray = test([1, 2, 3]) // 推断为 number[]

四、泛型类

这个⽤得⽐较少

typescript
class Test<T> { 
	value: T 
	constructor (value: T) { 
		this.value = value 
	} 
} 

const test1: Test<string> = new Test('a') 
const str1: string = test1.value 

const test2: Test<number> = new Test(1) 
const num1: number = test2.value