3

In actual development, we may have the following scenarios:

  1. There is a Student interface, which is used to correspond to the return type of the interface.
  2. In a StudentService, there is an update method in this method to update the Student.

Scenario Review

Student:

interface Student {
  id: number;
  // 学号
  no: number;
  // 姓名
  name: string;
  // 手机号
  phone: string;
  // 性别
  sex: boolean;
}

Now the logic is like this, when updating the student's information, we only allow the user to update the name and phone fields. At this point, we want to reflect in the StudentService.update method that only these two fields are allowed to be updated. We have two ways of writing:

The first is to directly declare the parameter type as Student:

class StudentService {
  void update(id: number, student: Student) {
  }
}

Second, declare the field type directly in the parameter:

class StudentService {
  void update(id: number, student: {name: string, phone: string}) {
  }
}

Disadvantage Analysis

The disadvantage of the first method is that we cannot directly obtain the updated student field in this method through the declaration of the update method, but its advantage is that it can quickly display the changes of the mobile phone .

The advantage of the second method is that the field to be updated can be directly obtained in the update method, but the disadvantage is that it cannot quickly respond to the field changes of the Student entity in the future.

suggestion

Actually I want a parameter declaration similar to the following:

class StudentService {
  void update(id: number, student: {name: string, phone: string} as Student) {
  }
}

But unfortunately, typescript does not support this way of writing, so as a second best, we can write it like this:

class StudentService {
  void update(id: number, student: {name: string, phone: string}) {
    student = student as Student;
  }
}

Simply add a type deduction to the first line of the function, so that:

  1. When the type of Student changes, we can automatically a syntax error in this line of code through the syntax check , and then make corrections.
  2. Since we directly declare each field in the parameters, instead of using Student for extensive declaration, we can directly obtain the specific update function of the update method.

潘杰
3.1k 声望239 粉丝