logo

目录

TypeScript最佳实践Tips
⚒️

TypeScript最佳实践Tips

你是否避免使用 "any"?

TypeScript 的 any 关键字是一把双刃剑。它表示一种可以是任何类型的类型,其中每个可能的属性和方法都存在,并且返回 any。它可以与任何类型进行转换,也是你告诉编译器“别管我”的方式。
然而,any 容易被用作一种依赖,导致你错过了 TypeScript 的主要好处,比如便捷的智能提示、重构支持和编译时的安全性!
 
Figure: Bad example – I can pass anything into this method, so I get bad output at run time (“undefined undefined”)
Figure: Bad example – I can pass anything into this method, so I get bad output at run time (“undefined undefined”)
 
Figure: Good example – using types means I get errors and intellisense support
Figure: Good example – using types means I get errors and intellisense support
如果你想编写更类型安全的代码,一般建议尽可能使用 unknown 而不是 any,因为它迫使你进行类型检查,并有助于在开发过程中及早发现错误。

是否对类型进行了简单描述?

这取决于个人喜好,不过在某些情况下你必须在 TypeScript 中定义类型,例如:
本章目录
    1v1免费职业咨询