持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第10天,点击查看活动详情
本文的翻译于<<Micro State Management with React Hooks>>, 特别感谢!! 本文的翻译于<<Effective TypeScript>>, 特别感谢!! ps: 本文会用简洁, 易懂的语言描述原书的所有要点. 如果能看懂这文章,将节省许多阅读时间. 如果看不懂,务必给我留言, 我回去修改.
技巧62:在设置noImplicitAny之前,别认为你代码迁移完成
将js转成ts已经是巨大的成就了,但是这不意味着结束。你下一步应该做的:打开noImplicitAny
选项(见技巧2)。
noImplicitAny
往往能找到你更多的错误。例如你可能为了快速修复class缺失的属性(见技巧61),修复结果如下:
class Chart {
indices: any;
// ...
}
indices可能是number组成的array,所以你这么修改:
class Chart {
indices: number[];
// ...
}
但是不幸的是:indices类型不对。这是class中的其他代码:
getRanges() {
for (const r of this.indices) {
const low = r[0]; // Type is any
const high = r[1]; // Type is any
// ...
}
}
显然,number[][]比number[]更准确,但是这里居然不报错。 当你打开noImplicitAny
选项后,就能发现:
getRanges() {
for (const r of this.indices) {
const low = r[0];
// ~~~~ Element implicitly has an 'any' type because
// type 'Number' has no index signature
const high = r[1];
// ~~~~ Element implicitly has an 'any' type because
// type 'Number' has no index signature
// ...
}
}
好的方法:在打开noImplicitAny
之前,先commit代码。然后打开noImplicitAny
,修复所有的bug后,再commit代码。
还有其他的一些设置提供更严格的类型检查:例如「strict」,但是打开noImplicitAny
是最重要的,能让你获得ts的大部分好处。当你进行严格的ts类型检查之前,让你的伙伴们提前适应ts。