Skip to main content

Typescript泛型

认识泛型

软件工程的主要目的是构建不仅仅明确和一致的API,还要让你的代码具有很强的复用性

将类型参数化

泛型简单实现:useState

function useState<Type>(initalState:Type):[Type,(newState:Type)=>void]{
let state = initalState
function setState(newState){
state = newState
}
return [state,setState]
}

const [count,setCount] = useState(111)

泛型传入多个参数

function foo<Type,Element>(arg:Type,arg2:Element){

}

泛型的常用缩写

  1. T:Type的缩写
  2. K、V:key和value的缩写,键值对
  3. E:Element的缩小,元素
  4. O:Object的缩小,对象

泛型接口

interface Ikun<Type>{
name:Type
age:number
slogan:Type
}

const kun:Ikun<string>={
name:'xiaowu',
age:18,
slogan:'aaa'

}

泛型类

class Point<Type>{
x:Type
y:Type
constructor(x:Type,y:Type){
this.x = x
this.y = y
}
}

泛型约束(Generic Constraints)

函数的类型丢失

interface IL{
length:number
}

function getLength<T extends IL>(arg:T){
return arg
}

const info1 = getLength('aaa')
const info2 = getLength(123)

映射类型(Mapped Types)、

只能使用type不能用interface

有时候一个类型需要基于另外一个类型,但你又不想拷贝一份,这时候可以考虑是哟映射类型

建立在签名类型上

type M<Type> = {
[aaa in keyof Type]:Type[aaa]
}

映射类型修饰符

 type M<Type> = {
-readonly [aaa in keyof Type]-?:Type[aaa]
}

内置工具和类型体操