10个写TypeScript代码的坏习惯

开发 前端
近几年 TypeScript 和 JavaScript 一直在稳步发展。我们在过去写代码时养成了一些习惯,而有些习惯却没有什么意义。以下是我们都应该改正的 10 个坏习惯。

近几年 TypeScript 和 JavaScript 一直在稳步发展。我们在过去写代码时养成了一些习惯,而有些习惯却没有什么意义。以下是我们都应该改正的 10 个坏习惯。

1. 不使用strict模式

(1) 这种习惯看起来是什么样的

没有用严格模式编写 tsconfig.json。

  1.   "compilerOptions": { 
  2.     "target": "ES2015", 
  3.     "module": "commonjs" 
  4.   } 

(2) 应该怎样

只需启用 strict 模式即可:

  1.   "compilerOptions": { 
  2.     "target": "ES2015", 
  3.     "module": "commonjs", 
  4.     "strict": true 
  5.   } 

(3) 为什么会有这种坏习惯

在现有代码库中引入更严格的规则需要花费时间。

(4) 为什么不该这样做

更严格的规则使将来维护代码时更加容易,使你节省大量的时间。

2. 用||定义默认值

(1) 这种习惯看起来是什么样的

使用旧的 || 处理后备的默认值:

  1. function createBlogPost (text: string, author: string, date?: Date) { 
  2.   return { 
  3.     text: text, 
  4.     author: author, 
  5.     date: date || new Date() 
  6.   } 

(2) 应该怎样

使用新的 ?? 运算符,或者在参数重定义默认值。

  1. function createBlogPost (text: string, author: string, date: Date = new Date()) 
  2.   return { 
  3.     text: text, 
  4.     author: author, 
  5.     date: date 
  6.   } 

(3) 为什么会有这种坏习惯

?? 运算符是去年才引入的,当在长函数中使用值时,可能很难将其设置为参数默认值。

(4) 为什么不该这样做

?? 与 || 不同,?? 仅针对 null 或 undefined,并不适用于所有虚值。

3. 随意使用any类型

(1) 这种习惯看起来是什么样的

当你不确定结构时,可以用 any 类型。

  1. async function loadProducts(): Promise<Product[]> { 
  2.   const response = await fetch('https://api.mysite.com/products') 
  3.   const products: any = await response.json() 
  4.   return products 

(2) 应该怎样

把你代码中任何一个使用 any 的地方都改为 unknown

  1. async function loadProducts(): Promise<Product[]> { 
  2.   const response = await fetch('https://api.mysite.com/products') 
  3.   const products: unknown = await response.json() 
  4.   return products as Product[] 

(3) 为什么会有这种坏习惯

any 是很方便的,因为它基本上禁用了所有的类型检查。通常,甚至在官方提供的类型中都使用了 any。例如,TypeScript 团队将上面例子中的 response.json() 的类型设置为 Promise

(4) 为什么不该这样做

它基本上禁用所有类型检查。任何通过 any 进来的东西将完全放弃所有类型检查。这将会使错误很难被捕获到。

4. val as SomeType

(1) 这种习惯看起来是什么样的

强行告诉编译器无法推断的类型。

  1. async function loadProducts(): Promise<Product[]> { 
  2.   const response = await fetch('https://api.mysite.com/products') 
  3.   const products: unknown = await response.json() 
  4.   return products as Product[] 

(2) 应该怎样

这正是 Type Guard 的用武之地。

  1. function isArrayOfProducts (obj: unknown): obj is Product[] { 
  2.   return Array.isArray(obj) && obj.every(isProduct) 
  3.  
  4. function isProduct (obj: unknown): obj is Product { 
  5.   return obj != null 
  6.     && typeof (obj as Product).id === 'string' 
  7.  
  8. async function loadProducts(): Promise<Product[]> { 
  9.   const response = await fetch('https://api.mysite.com/products') 
  10.   const products: unknown = await response.json() 
  11.   if (!isArrayOfProducts(products)) { 
  12.     throw new TypeError('Received malformed products API response') 
  13.   } 
  14.   return products 

(3) 为什么会有这种坏习惯

从 JavaScript 转到 TypeScript 时,现有的代码库通常会对 TypeScript 编译器无法自动推断出的类型进行假设。在这时,通过 as SomeOtherType 可以加快转换速度,而不必修改 tsconfig 中的设置。

(4) 为什么不该这样做

Type Guard 会确保所有检查都是明确的。

5. 测试中的as any

(1) 这种习惯看起来是什么样的

编写测试时创建不完整的用例。

  1. interface User { 
  2.   id: string 
  3.   firstName: string 
  4.   lastName: string 
  5.   email: string 
  6.  
  7. test('createEmailText returns text that greats the user by first name', () => { 
  8.   const user: User = { 
  9.     firstName: 'John' 
  10.   } as any 
  11.    
  12.   expect(createEmailText(user)).toContain(user.firstName) 

(2) 应该怎样

如果你需要模拟测试数据,请将模拟逻辑移到要模拟的对象旁边,并使其可重用。

  1. interface User { 
  2.   id: string 
  3.   firstName: string 
  4.   lastName: string 
  5.   email: string 
  6.  
  7. class MockUser implements User { 
  8.   id = 'id' 
  9.   firstName = 'John' 
  10.   lastName = 'Doe' 
  11.   email = 'john@doe.com' 
  12.  
  13. test('createEmailText returns text that greats the user by first name', () => { 
  14.   const user = new MockUser() 
  15.  
  16.   expect(createEmailText(user)).toContain(user.firstName) 

(3) 为什么会有这种坏习惯

在给尚不具备广泛测试覆盖条件的代码编写测试时,通常会存在复杂的大数据结构,但要测试的特定功能仅需要其中的一部分。短期内不必关心其他属性。

(4) 为什么不该这样做

在某些情况下,被测代码依赖于我们之前认为不重要的属性,然后需要更新针对该功能的所有测试。

6. 可选属性

(1) 这种习惯看起来是什么样的

将属性标记为可选属性,即便这些属性有时不存在。

  1. interface Product { 
  2.   id: string 
  3.   type: 'digital' | 'physical' 
  4.   weightInKg?: number 
  5.   sizeInMb?: number 

(2) 应该怎样

明确哪些组合存在,哪些不存在。

  1. interface Product { 
  2.   id: string 
  3.   type: 'digital' | 'physical' 
  4.  
  5. interface DigitalProduct extends Product { 
  6.   type: 'digital' 
  7.   sizeInMb: number 
  8.  
  9. interface PhysicalProduct extends Product { 
  10.   type: 'physical' 
  11.   weightInKg: number 

(3) 为什么会有这种坏习惯

将属性标记为可选而不是拆分类型更容易,并且产生的代码更少。它还需要对正在构建的产品有更深入的了解,并且如果对产品的设计有所修改,可能会限制代码的使用。

(4) 为什么不该这样做

类型系统的最大好处是可以用编译时检查代替运行时检查。通过更显式的类型,能够对可能不被注意的错误进行编译时检查,例如确保每个 DigitalProduct 都有一个 sizeInMb。

7. 用一个字母通行天下

(1) 这种习惯看起来是什么样的

用一个字母命名泛型

  1. function head<T> (arr: T[]): T | undefined { 
  2.   return arr[0] 

(2) 应该怎样

提供完整的描述性类型名称。

  1. function head<Element> (arr: Element[]): Element | undefined { 
  2.   return arr[0] 

(3) 为什么会有这种坏习惯

这种写法最早来源于C++的范型库,即使是 TS 的官方文档也在用一个字母的名称。它也可以更快地输入,只需要简单的敲下一个字母 T 就可以代替写全名。

(4) 为什么不该这样做

通用类型变量也是变量,就像其他变量一样。当 IDE 开始向我们展示变量的类型细节时,我们已经慢慢放弃了用它们的名称描述来变量类型的想法。例如我们现在写代码用 const name ='Daniel',而不是 const strName ='Daniel'。同样,一个字母的变量名通常会令人费解,因为不看声明就很难理解它们的含义。

8. 对非布尔类型的值进行布尔检查

(1) 这种习惯看起来是什么样的

通过直接将值传给 if 语句来检查是否定义了值。

  1. function createNewMessagesResponse (countOfNewMessages?: number) { 
  2.   if (countOfNewMessages) { 
  3.     return `You have ${countOfNewMessages} new messages` 
  4.   } 
  5.   return 'Error: Could not retrieve number of new messages' 

(2) 应该怎样

明确检查我们所关心的状况。

  1. function createNewMessagesResponse (countOfNewMessages?: number) { 
  2.   if (countOfNewMessages !== undefined) { 
  3.     return `You have ${countOfNewMessages} new messages` 
  4.   } 
  5.   return 'Error: Could not retrieve number of new messages' 

(3) 为什么会有这种坏习惯

编写简短的检测代码看起来更加简洁,使我们能够避免思考实际想要检测的内容。

(4) 为什么不该这样做

也许我们应该考虑一下实际要检查的内容。例如上面的例子以不同的方式处理 countOfNewMessages 为 0 的情况。

9. ”棒棒“运算符

(1) 这种习惯看起来是什么样的

将非布尔值转换为布尔值。

  1. function createNewMessagesResponse (countOfNewMessages?: number) { 
  2.   if (!!countOfNewMessages) { 
  3.     return `You have ${countOfNewMessages} new messages` 
  4.   } 
  5.   return 'Error: Could not retrieve number of new messages' 

(2) 应该怎样明

确检查我们所关心的状况。

  1. function createNewMessagesResponse (countOfNewMessages?: number) { 
  2.   if (countOfNewMessages !== undefined) { 
  3.     return `You have ${countOfNewMessages} new messages` 
  4.   } 
  5.   return 'Error: Could not retrieve number of new messages' 

(3) 为什么会有这种坏习惯

对某些人而言,理解 !! 就像是进入 JavaScript 世界的入门仪式。它看起来简短而简洁,如果你对它已经非常习惯了,就会知道它的含义。这是将任意值转换为布尔值的便捷方式。尤其是在如果虚值之间没有明确的语义界限时,例如 null、undefined 和 ''。

(4) 为什么不该这样做

与很多编码时的便捷方式一样,使用 !! 实际上是混淆了代码的真实含义。这使得新开发人员很难理解代码,无论是对一般开发人员来说还是对 JavaScript 来说都是新手。也很容易引入细微的错误。在对“非布尔类型的值”进行布尔检查时 countOfNewMessages为 0 的问题在使用 !! 时仍然会存在。

10. != null

(1) 这种习惯看起来是什么样的

棒棒运算符的小弟 ! = null使我们能同时检查 null 和 undefined。

  1. function createNewMessagesResponse (countOfNewMessages?: number) { 
  2.   if (countOfNewMessages != null) { 
  3.     return `You have ${countOfNewMessages} new messages` 
  4.   } 
  5.   return 'Error: Could not retrieve number of new messages' 

(2) 应该怎样

明确检查我们所关心的状况。

  1. function createNewMessagesResponse (countOfNewMessages?: number) { 
  2.   if (countOfNewMessages !== undefined) { 
  3.     return `You have ${countOfNewMessages} new messages` 
  4.   } 
  5.   return 'Error: Could not retrieve number of new messages' 

(3) 为什么会有这种坏习惯

如果你的代码在 null 和 undefined 之间没有明显的区别,那么 != null 有助于简化对这两种可能性的检查。

(4) 为什么不该这样做

尽管 null 在 JavaScript早期很麻烦,但 TypeScript 处于 strict 模式时,它却可以成为这种语言中宝贵的工具。一种常见模式是将 null 值定义为不存在的事物,将 undefined 定义为未知的事物,例如 user.firstName === null 可能意味着用户实际上没有名字,而 user.firstName === undefined 只是意味着我们尚未询问该用户(而 user.firstName === 的意思是字面意思是 '' 。

 

责任编辑:赵宁宁 来源: 前端先锋
相关推荐

2022-09-11 15:02:21

JavaScriptTypeScript数据

2019-11-28 18:51:07

PythonPHP编程语言

2018-11-26 09:40:39

Python坏习惯编程语言

2018-10-17 11:20:55

SQL数据库程序员

2012-05-22 00:16:47

2021-11-01 22:39:14

程序员专业技术

2020-12-15 16:44:48

代码程序运行

2009-07-21 14:32:02

IT人习惯

2019-01-25 17:21:04

程序员坏习惯

2018-01-11 13:57:36

程序员技能开发者

2017-09-02 15:38:16

2013-04-11 12:58:47

2013-01-22 11:57:29

IT工作者加班

2021-02-06 14:05:29

代码语言bug

2013-09-03 09:54:15

Web开发

2012-07-17 11:13:44

程序员

2024-01-15 06:45:29

Go编程代码

2024-01-07 13:25:32

Go编程代码

2009-07-20 14:02:49

66天习惯养成改正坏习惯

2013-07-24 14:17:48

点赞
收藏

51CTO技术栈公众号