Typescript comes with a lot of tooltypes, and there are a lot of tricks you can learn by looking at the source code. Here are some very useful tips:

  1. Query the list of objects based on some properties of the Model
type Student = { / / define the model
	id: number; / / the primary key
	name: string;
	age: number;
}

interface IQuery<T> {
  select(params: Partial<T>): T[];
}

class QueryStudent implements IQuery<Student> {
  select(params: Partial<Student>): Student[] {
    // @todo}}Copy the code

Using Partial and T types properly can save a lot of type declarations. Partial sets all fields in a type to optional, so that the key of the params parameter is locked to the key that T has.

  1. Update data according to model

When updating data, it is usually necessary to specify a unique ID. In this case, we need to use type inference:

type PropsRequired<T, S extends keyof T> = {
  [k inS]-? : T[k] };// This place can also be Required
      
       >
      
type ModelUpdateParams<T, S extends keyof T> = Partial<Pick<T, Exclude<keyof T, S>>> & PropsRequired<T, S>; // use the following tools to Omit anything: Partical< T, S>> & Required< T, S>>;
class StudentModel {
	public update(params: ModelUpdateParams<Student, 'id'>) {
		// @todo }}Copy the code

The derivation of the ModelUpdateParams type is to extract non-required fields into Paritial and then combine them with required fields so that the update parameter must contain the specified field name ID.

  1. Class the valueOf derived

There are workarounds for seeing keyof but not valueOf in typescript documentation:

type FunctionPropKeys<T> = {
  [k in keyof T]: T[k] extends Function ? k : never;
}[keyof T]; // This is similar to valueOf, fetching the key of the function type

type FunctionProps<T> = Pick<T, FunctionPropKeys<T>>; // We declare a type to extract function attributes
Copy the code