preface

In the process of learning TypeScript, I found that certain UtilityTypes were not well understood, so I restudied the documentation systematically. TypeScript provides several UtilityTypes to facilitate common type conversions. These utilities are available globally.

UtilityTypes document links: www.typescriptlang.org/docs/handbo…

Partial

Converts all properties of T passed in by the generic type to optional properties. The type returned can be any subset of T.

interface Person {
  name: string.age: number
}

Type Person1 = {name? : string; age? : number; }
type Person1 = Partial<Person> 

const p: Person = {
  name: 'lin'.age: 18
}

const p1: Person1 = {
  name: 'lin'
}
Copy the code

Source:

type Partial<T> = {
    [P inkeyof T]? : T[P]; };Copy the code

Keyof T get T the key values in combination, the example T here is the Person quite so ‘name’ | ‘age, the in keyword traversal keyof return values for the new type the new name and age properties,? The operator defines all properties as optional.

Required

Converts all properties in T passed in by the generic type to required properties, as opposed to Partial.

interfacePerson { name? :string, age? :number
}

type Person1 = Required<Person> Type Person1 = {name: string; age: number; }

const p: Person = {
  name: 'lin'
}

// Error message: type "{name: string; The attribute "age" is missing in}", but is Required in the type "Required
      
       ".
      
const p1: Person1 = {
  name: 'lin'
}
Copy the code

Source:

type Required<T> = {
    [P inkeyof T]-? : T[P]; };Copy the code

Contrary to Partial, pass -? The operator removes all optional attributes.

Readonly

Converts all properties passed in T by the generic type to read-only properties.

interface Person {
  name: string
}

type Person1 = Readonly<Person> Type Person1 = {readonly name: string; }

const p: Person1 = {
  name: 'lin'
}

// Error: "name" cannot be assigned because it is read-only.
p.name = 'zhen'
Copy the code

Source:

type Readonly<T> = {
    readonly [P in keyof T]: T[P];
};
Copy the code

Use the readonly keyword to make all properties read-only.

Record<K, T>

Create an object type whose key is of type K and whose value is of type T.

interface CatInfo {
  age: number;
  breed: string;
}

type CatName = "miffy" | "boris" | "mordred";

const cats: Record<CatName, CatInfo> = {
  miffy: { age: 10.breed: "Persian" },
  boris: { age: 5.breed: "Maine Coon" },
  mordred: { age: 16.breed: "British Shorthair"}};// Boris type: CatInfo
cats.boris;
Copy the code

Source:

type Record<K extends keyof any, T> = {
    [P in K]: T;
};
Copy the code

Pick<T, K>

Construct the type by selecting a set of attributes K(string literals or a union of string literals) from the generic T passed in.

interface Todo {
  title: string;
  description: string;
  completed: boolean;
}

// Equivalent type TodoPreview = {title: string; completed: boolean; }
type TodoPreview = Pick<Todo, "title" | "completed">;

const todo: TodoPreview = {
  title: "Clean room".completed: false};Copy the code

Source:

type Pick<T, K extends keyof T> = {
    [P in K]: T[P];
};
Copy the code

Specifies that the generic type K must be a subset of the key in the generic type T. In the example above, K must be ‘title’ | ‘description’ | ‘completed’

Omit<T,K>

Select a set of properties K from the generic T passed in and remove the others, as opposed to Pick.

interface Todo {
  title: string;
  description: string;
  completed: boolean;
  createdAt: number;
}
// Equivalent type TodoPreview = {title: string; completed: boolean; createdAt: number; }
type TodoPreview = Omit<Todo, "description">;

const todo: TodoPreview = {
  title: "Clean room".completed: false.createdAt: 1615544252770};Copy the code

Source:

type Omit<T, K extends keyof any> = Pick<T, Exclude<keyof T, K>>;
Copy the code

Using a combination of Pick and Exclude, use Exclude to Exclude all attributes in T except those containing K, and use Pick to recreate a new type.

Parameters

You can get the types of the parameters in a function by constructing a tuple type from the types used in the parameters of the function type T.

const fn = (a: string.b: number) :void= > {}

const fn1 = <T>(arg: T): T= > arg

// type p1 = [a: string, b: number
type p1 = Parameters<typeof fn>

// type p2 = [arg: unknown]
type p2 = Parameters<typeof fn1>

// type p3 = unknown[]
type p3 = Parameters<any>

// type p4 = never
type p4 = Parameters<never>

// Type "string" does not satisfy the constraint "(... Args: any => any ".
// A generic must pass in the type definition of the function
type p5 = Parameters<'lin'>
Copy the code

Source:

type Parameters<T extends(... args:any) = >any> = T extends(... args: infer P) =>any ? P : never;
Copy the code

ReturnType

Gets the type of the value returned by function type T.

const fn = () = > {
  return {
    name: 'lin'.age: 18}}const fn1 = () = > {
  return [18.'lin']}// type r1 = { name: string; age: number; }
type r1 = ReturnType<typeof fn>

// type r2 = (string | number)[]
type r2= ReturnType<typeof fn1>

// type r3 = any
type r3 = ReturnType<any>

// type r4 = never
type r4 = ReturnType<never>

// Type "string" does not satisfy the constraint "(... Args: any => any ".
// A generic must pass in the type definition of the function
type r5 = ReturnType<'lin'>
Copy the code

Source:

type ReturnType<T extends(... args:any) = >any> = T extends(... args:any) => infer R ? R : any;
Copy the code