Generics

Introduction to TypeScript Generics
The introduction to the official website is very detailed. In fact, generics are things that program types. They are not complicated at all, and those who can write code functions are well understood.
If you want to learn generics well, you only need to master two basic knowledge:

  1. keyof gets used
  2. in traversal use
    Oh, and a generic constraint, the key syntax extends

Introduction to basic knowledge

First define an interface interface as follows:

interface IUser {
    id: number;
    name: string;
    age?: number;
    info?: string;
}

Next, the use of keyof is introduced. First, use keyof to obtain all the properties of the interface IUser, as follows:

type IUserKeys = keyof IUser;

image.png

Then introduce the use of in to traverse properties, as follows:

type IKeys = {
    [P in keyof IUser]: IUser[P]
}

image.png

It's simple, just like writing the simplest program. Okay, let's get to the topic, let's analyze several common type tools built in typescript.

Preset type

  • Partial<T>
    It is to make all the attributes of an interface optional, and use the above keyof and in plus optional operator to directly implement it, as follows:

    type Partial<T> = {
      [P in keyof T]?: T[P];
    };
  • Required<T>
    All attributes are set to required, and the same as the above, just remove the optional operator:

    type Required<T> = {
      [P in keyof T]-?: T[P];
    };
  • Readonly<T>
    Set the property to read-only, and in the same way, add the readonly modifier:

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

    The above three are very simple, easy to understand, right? Next, implement some slightly more complex, of course not difficult

  • Pick<T, K>
    The meaning is to select the department type in the interface. A key point here is that this part must exist in the interface, so generic constraints need to be added. The implementation is to use the extends keyword to indicate that K is constrained by (keyof T), as follows:

    type Pick<T, K extends keyof T> = {
      [P in K]: T[P];
    };
  • Record<K, T>
    The meaning is to set the type of attribute K to type T, traverse K, and set it to T.

    type Record<K extends keyof any, T> = {
      [P in K]: T;
    };
  • Exclude<T, U>
    The meaning is to remove the unwanted U part from T, such as 'a' | 'b' | 'c', remove 'c':

    type Exclude<T, U> = T extends U ? never : T;
  • Qmit<T, K>
    Constructs an interface of type T, but excludes the properties in K from it. This needs to be thought about. The implementation idea is to use Pick to select the desired attributes, and then the desired attributes are generally Excluded to exclude the ones in K to obtain.

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

donglegend
910 声望82 粉丝

长安的风何时才能吹到边梁?