这是我参与11月更文挑战的第1天,活动详情查看:2021最后一次更文挑战
有时候在用一个工具或者第三方库的时候你是不是很想打开源码,看见很多typescript的类型,还有很多泛型贡工具类,这篇文章会给你分享五个常见的泛型工具类,助你源码阅读又少一个障碍。
Partial
Partial的作用就是吧某个类型中的属性都变成可选项
//源码:keyof T拿到T的所有属性名,用in进行遍历将属性名赋值给P,
用T[P]拿到属性值,?把所有属性都变成可选的
type Partial<T>={
[P in keyof T]?:T[p]
}
案例:Partial将Todo中的属性都变为可选的
interface Todo{
title:string,
description:string
}
function updateTodo(todo:Todo,fieldsToUpdate:Partial<Todo>){
return {...todo,...fieldsToUpdate}
}
const todo1={
title:'coding',
description:'coding to day by day'
}
const todo2=updateTodo(todo1,{
description:'day day up'
})
console.log(todo2); //{ title: 'coding', description: 'day day up' }
Record
Record<K extends keyof any,T>的作用是将K中的属性的值都转为T类型
K extends keyof T 确保参数key一定是对象中含有的键
type Record<K extends keyof any,T>={
[P in K]:T
}
案例:
interface PageInfo{
title:string
}
type Page = "home"|"about"|"contact"
const x:Record<Page,PageInfo>={
about:{title:"about"},
contact:{title:"contact"},
home:{title:'home'}
}
console.log(x);
Pick
Pick<T,K extends keyof T>作用是将某个类型的子属性挑出来,变成包含这些属性的子类型
type Pick<T,K extends keyof T> ={
[P in K]:T[P]
}
案例:
interface Todo{
title:string,
description:string,
completed:boolean
}
type TodoPreview = Pick<Todo,"title"|"completed">
const todo:TodoPreview={
title:"doSomething",
completed:true
}
console.log(todo);//{ title: 'doSomething', completed: true }
Exclude
Exclude<T,U>的作用就是将某个类型中的属于另一个类型移除掉
//源码:把T中的U移除掉
type Exclude<T,U> = T extends U ? never :T
案例:
type T0 =Exclude<'a'|'b'|'c','a'>
type T1 =Exclude<string|number|(()=>void),Function>
const test2:T1=function(){ //报错
console.log('111');
}
ReturnType
ReturnType的作用就是获取函数T的返回类型
type ReturnType<T extends (...args: any) => any> =
T extends (...args: any) => infer R ? R : any;
案例:
type T1 = ReturnType<(s: string) => void>; // void