This is the first day of my participation in the Gwen Challenge in November. Check out the details: the last Gwen Challenge in 2021
If you’re tempted to open source when using a tool or third-party library, you’ll see a lot of typescript types, as well as a lot of generic utility classes, this article will share five common generic utility classes to help you read the source code.
Partial
Partial is used to make all properties of a type optional
T[P] = T[P] = T[P] = T[P]; Type Partial<T>={[P in keyof T]? :T[p] }Copy the code
Example: Partial makes all attributes in Todo optional
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' }Copy the code
Record
Type Record<K extends Keyof any,T>={Record<K extends Keyof any,T>={type Record<K extends Keyof any,T>={ [P in K]:T }Copy the code
Case study:
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);
Copy the code
Pick
Type Pick<T,K extends Keyof T> ={[P in K]:T[P]} Pick<T,K extends Keyof T> ={[P in K]:T[P]}Copy the code
Case study:
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 }Copy the code
Exclude
Exclude<T,U> removes items of one type from another
Type Exclude<T,U> = T extends U? never :TCopy the code
Case study:
Type T0 = Exclude < 'a' | 'b' | 'c', 'a' > type T1 = Exclude < string | number | () = > (void), Function > const test2: T1 = Function () {/ / an error console.log('111'); }Copy the code
ReturnType
The purpose of ReturnType is to get the ReturnType of T
type ReturnType<T extends (... args: any) => any> = T extends (... args: any) => infer R ? R : any;Copy the code
Case study:
type T1 = ReturnType<(s: string) => void>; // void
Copy the code