关于前端:在前端开发中一种规划参数类型的新思路

3次阅读

共计 1020 个字符,预计需要花费 3 分钟才能阅读完成。

在理论的开发中,咱们可能有如下场景:

  1. 有一个 Student 接口,用于与接口的返回类型绝对应。
  2. 在一个 StudentService,该办法中有一个 update 办法,用于更新 Student.

情景回顾

Student:

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

当初逻辑是这样,在更新学生的信息时,咱们仅容许用户更新 name 以及 phone 字段。此时咱们想在 StudentService.update 办法中体现仅仅容许更新这两个字段,咱们有两种写法:

第一种,间接将参数类型申明为 Student:

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

第二种,间接在参数中申明字段类型:

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

弊病剖析

第一种办法的弊病在于咱们无奈通过 update 办法的申明能间接失去该办法中更新学生的字段,但其劣势在于能够疾速的显示 Student 实体的变更,比方在前期中咱们将 phone 字段变更为mobile

第二种办法的劣势是能够在 update 办法间接得出要更新的字段,但弊病是无奈疾速的响应 Student 实体在日后的字段变更。

倡议计划

其实我是想要一个相似于如下的参数申明:

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

但很遗憾的是 typescript 并不反对这种写法,那么退而求其次,咱们能够这样写:

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

简略的在函数的第一行减少一个类型推导,这样一来:

  1. Student 类型产生变更时,咱们能够通过语法查看 主动 地发现该行代码产生了语法错误,进而进行修改。
  2. 因为在参数中咱们间接申明了各个字段,而不是应用 Student 进行宽泛的申明,咱们能够间接获取到该 update 办法具体更新的性能。
正文完
 0