Make writing a habit together! This is the fifth day of my participation in the “Gold Digging Day New Plan · April More text Challenge”. Click here for more details.
As more and more projects write in TypeScript, we all know that TypeScript is a superset of JavaScript that provides powerful typing and syntax enhancements to JavaScript to reduce errors during project development. TypeScript has a lot of tool types built into it, so I’ll take you through them.
This is the third article in a series
NonNullable
NonNullable removes the null, undefined attribute from a type.
chestnuts
// type NonNullable<T> = T extends null ? never : T
type stringType=NonNullable<string|undefined|null>
// type stringType = string
Copy the code
Analysis of the
Return never if type T can be assigned to NULL, T otherwise.
type NonNullable<T> = T extends null ? never : T
Copy the code
Parameters
Parameters is used to get the parameter type of a function.
chestnuts
export default function fun1(x: number, y: number, z: number) {
 console.log(x, y, z);
 return { x, y, z };
}
​
type p1=Parameters<(name:number) = >void>
// type p1 = [name: number]
​
type p2=Parameters<<T>(arg:T) = >T>
// type p2 = [arg: unknown]
​
// Get the argument type of fun1
type p3=Parameters<typeof fun1>
// [x: number, y: number, z: number]
​
/ / analysis
// type Parameters
any> = T extends (... args: infer P) => any ? P : never
Copy the code
Analysis of the
Type T can infer the parameter types of P function through the infer keyword.
type Parameters<T extends(... args:any) = >any> = T extends(... args: infer P) =>any ? P : never
Copy the code
ConstructorParameters
ConstructorParameters The user gets the parameter type of a constructor.
chestnuts
class Person {
 name: string;
 age: number;
 constructor(name: string, age: number) {
  this.name = name;
  this.age = age; }}type PT=ConstructorParameters<typeof Person>
// type PT = [name: string, age: number]
​
type ET =ConstructorParameters<ErrorConstructor>
// type ET = [message?: string]
​
type NT =ConstructorParameters<null>
// type NT = unknown[]
​
type AT =ConstructorParameters<any>
// type AT = unknown[]
Copy the code
Analysis of the
type ConstructorParameters<T extends abstract new(... args:any) = >any> = T extends abstract new(... args: infer P) =>any ? P : never
Copy the code
ReturnType
ReturnType is used to get the return value type of a function.
chestnuts
function f1(name: string) :string {
 return name;
}
​
type f1Type = ReturnType<typeof f1>;
// type f1Type = string
​
function f2<T> (name: T) :T {
 return name;
}
​
type f2Type = ReturnType<typeof f2>;
// type f2Type = unknown
​
Copy the code
Analysis of the
type ReturnType<T extends(... args:any) = >any> = T extends(... args:any) => infer R ? R : any
Copy the code