wisetc / practice

Practice conclusion
5 stars 0 forks source link

JSDoc 加 TypeScript 对前端 bug 调试中的应用 #29

Open wisetc opened 5 years ago

wisetc commented 5 years ago

偶有缺乏经验的前端工程师没有受过强类型语言的训练,在编写方法代码的时候没有变量类型的意识,容易混用对象和字符串,出现乱赋值的情形,结果是数据在运行的过程中被任意篡改,大大提高出现 bug 的几率,并且出现 bug 的时候不容易定位。

比如下面的这位伙伴写的代码,

    let house = childValue || ''
    const params = {
      houseId: house.houseId ,
      houseName: this.setHouseName(),
      pwdType: 'DYNAMIC',
      opUserId: getUserId(),
      opUserName: getUsername(),
      smsPhone: getPhone(),
      smsUserName,
      houseIdList: this.state.houseList
    }

开启// @ts-check 或者 "checkJs": true 之后,编辑器提示了一个错误,

image

Property 'houseId' does not exist on type 'string'.ts(2339)

然后,需要跟踪下 childValue 这个 this.state 的属性,发现其来自于接口的数据,经过了一些变换,

image

可以看到 childValue 的类型为 any,

当为变量 children 寻找类型时,发现其其实是对象数组,当定义了 House 这种类型时,childValue 的类型也就豁然开朗了,

/**
 * @typedef {object} House
 * @property {string} houseId
 * @property {string} houseSpaceName
 */

定义 children 的类型,

/** @type {House[]} */

childValue 的类型为

(property) childValue: string | House

image

也就是 childValue 乱赋值空字符串。