一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第22天,点击查看活动详情。
本文的翻译于<<Effective TypeScript>>, 特别感谢!! ps: 本文会用简洁, 易懂的语言描述原书的所有要点. 如果能看懂这文章,将节省许多阅读时间. 如果看不懂,务必给我留言, 我回去修改.
技巧30:不要在注释中写类型信息
这段代码有什么问题?
/**
* Returns a string with the foreground color.
* Takes zero or one arguments. With no arguments, returns the
* standard foreground color. With one
argument, returns the foreground color
* for a particular page.
*/
function getForegroundColor(page?: string) {
return page === 'login' ? {r: 127, g: 127, b: 127} : {r: 0, g: 0, b: 0};
}
代码和注释不一致!我们改相信哪个?很难说,在这种情况下我们直接认定:代码和注释都有错!
我们具体看看注释有什么问题:
- 注释说函数返回 string 类型。代码却返回 object 类型。
- 注释说函数接受1个或者0个参数。函数类型签名
getForegroundColor(page?: string)已经说明了这一点。重复了 - 注释写的比你的代码还长。
为什么不要在注释中重复类型信息?
- ts 类型声明系统由一群几十年的经验丰富的程序员设计。所以它具有:紧凑,描述性,可读性等优点。绝对比你的注释散文要好!
- 从你一开始写代码,ts 编译器就强制同步检查你的类型。有的人代码升级,却忘记更新注释。 3.通过ts类型检查,你就可以重复相信你的代码。
一个好的注释长啥样?
/** Get the foreground color for the application or a specific page. */
function getForegroundColor(page?: string): Color {
// ...
}
如果想描述一个复杂参数可以用类似@param JSDoc的注释,具体的可以见 技巧48
只读参数也不要用注释来表达:
** Does not modify nums */
function sort(nums: number[]) { /* ... */ }
而是应该用 readonly 参数:
function sort(nums: readonly number[]) { /* ... */ }
同时在变量命名上,也有几点要注意:
- 避免使用
ageNum这样的命名,应该命名age,然后指定它的 type 为 number - 联合类型应该尽量在命名上体现联合。
timeMs好于time,temperatureC好于temperature