自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

10個寫TypeScript代碼的壞習(xí)慣

開發(fā) 前端
近幾年 TypeScript 和 JavaScript 一直在穩(wěn)步發(fā)展。我們在過去寫代碼時養(yǎng)成了一些習(xí)慣,而有些習(xí)慣卻沒有什么意義。以下是我們都應(yīng)該改正的 10 個壞習(xí)慣。

近幾年 TypeScript 和 JavaScript 一直在穩(wěn)步發(fā)展。我們在過去寫代碼時養(yǎng)成了一些習(xí)慣,而有些習(xí)慣卻沒有什么意義。以下是我們都應(yīng)該改正的 10 個壞習(xí)慣。

1. 不使用strict模式

(1) 這種習(xí)慣看起來是什么樣的

沒有用嚴(yán)格模式編寫 tsconfig.json。

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

(2) 應(yīng)該怎樣

只需啟用 strict 模式即可:

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

(3) 為什么會有這種壞習(xí)慣

在現(xiàn)有代碼庫中引入更嚴(yán)格的規(guī)則需要花費時間。

(4) 為什么不該這樣做

更嚴(yán)格的規(guī)則使將來維護(hù)代碼時更加容易,使你節(jié)省大量的時間。

2. 用||定義默認(rèn)值

(1) 這種習(xí)慣看起來是什么樣的

使用舊的 || 處理后備的默認(rèn)值:

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

(2) 應(yīng)該怎樣

使用新的 ?? 運算符,或者在參數(shù)重定義默認(rèn)值。

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

(3) 為什么會有這種壞習(xí)慣

?? 運算符是去年才引入的,當(dāng)在長函數(shù)中使用值時,可能很難將其設(shè)置為參數(shù)默認(rèn)值。

(4) 為什么不該這樣做

?? 與 || 不同,?? 僅針對 null 或 undefined,并不適用于所有虛值。

3. 隨意使用any類型

(1) 這種習(xí)慣看起來是什么樣的

當(dāng)你不確定結(jié)構(gòu)時,可以用 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) 應(yīng)該怎樣

把你代碼中任何一個使用 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) 為什么會有這種壞習(xí)慣

any 是很方便的,因為它基本上禁用了所有的類型檢查。通常,甚至在官方提供的類型中都使用了 any。例如,TypeScript 團(tuán)隊將上面例子中的 response.json() 的類型設(shè)置為 Promise 。

(4) 為什么不該這樣做

它基本上禁用所有類型檢查。任何通過 any 進(jìn)來的東西將完全放棄所有類型檢查。這將會使錯誤很難被捕獲到。

4. val as SomeType

(1) 這種習(xí)慣看起來是什么樣的

強(qiáng)行告訴編譯器無法推斷的類型。

  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) 應(yīng)該怎樣

這正是 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) 為什么會有這種壞習(xí)慣

從 JavaScript 轉(zhuǎn)到 TypeScript 時,現(xiàn)有的代碼庫通常會對 TypeScript 編譯器無法自動推斷出的類型進(jìn)行假設(shè)。在這時,通過 as SomeOtherType 可以加快轉(zhuǎn)換速度,而不必修改 tsconfig 中的設(shè)置。

(4) 為什么不該這樣做

Type Guard 會確保所有檢查都是明確的。

5. 測試中的as any

(1) 這種習(xí)慣看起來是什么樣的

編寫測試時創(chuàng)建不完整的用例。

  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) 應(yīng)該怎樣

如果你需要模擬測試數(shù)據(jù),請將模擬邏輯移到要模擬的對象旁邊,并使其可重用。

  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) 為什么會有這種壞習(xí)慣

在給尚不具備廣泛測試覆蓋條件的代碼編寫測試時,通常會存在復(fù)雜的大數(shù)據(jù)結(jié)構(gòu),但要測試的特定功能僅需要其中的一部分。短期內(nèi)不必關(guān)心其他屬性。

(4) 為什么不該這樣做

在某些情況下,被測代碼依賴于我們之前認(rèn)為不重要的屬性,然后需要更新針對該功能的所有測試。

6. 可選屬性

(1) 這種習(xí)慣看起來是什么樣的

將屬性標(biāo)記為可選屬性,即便這些屬性有時不存在。

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

(2) 應(yīng)該怎樣

明確哪些組合存在,哪些不存在。

  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) 為什么會有這種壞習(xí)慣

將屬性標(biāo)記為可選而不是拆分類型更容易,并且產(chǎn)生的代碼更少。它還需要對正在構(gòu)建的產(chǎn)品有更深入的了解,并且如果對產(chǎn)品的設(shè)計有所修改,可能會限制代碼的使用。

(4) 為什么不該這樣做

類型系統(tǒng)的最大好處是可以用編譯時檢查代替運行時檢查。通過更顯式的類型,能夠?qū)赡懿槐蛔⒁獾腻e誤進(jìn)行編譯時檢查,例如確保每個 DigitalProduct 都有一個 sizeInMb。

7. 用一個字母通行天下

(1) 這種習(xí)慣看起來是什么樣的

用一個字母命名泛型

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

(2) 應(yīng)該怎樣

提供完整的描述性類型名稱。

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

(3) 為什么會有這種壞習(xí)慣

這種寫法最早來源于C++的范型庫,即使是 TS 的官方文檔也在用一個字母的名稱。它也可以更快地輸入,只需要簡單的敲下一個字母 T 就可以代替寫全名。

(4) 為什么不該這樣做

通用類型變量也是變量,就像其他變量一樣。當(dāng) IDE 開始向我們展示變量的類型細(xì)節(jié)時,我們已經(jīng)慢慢放棄了用它們的名稱描述來變量類型的想法。例如我們現(xiàn)在寫代碼用 const name ='Daniel',而不是 const strName ='Daniel'。同樣,一個字母的變量名通常會令人費解,因為不看聲明就很難理解它們的含義。

8. 對非布爾類型的值進(jìn)行布爾檢查

(1) 這種習(xí)慣看起來是什么樣的

通過直接將值傳給 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) 應(yīng)該怎樣

明確檢查我們所關(guān)心的狀況。

  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) 為什么會有這種壞習(xí)慣

編寫簡短的檢測代碼看起來更加簡潔,使我們能夠避免思考實際想要檢測的內(nèi)容。

(4) 為什么不該這樣做

也許我們應(yīng)該考慮一下實際要檢查的內(nèi)容。例如上面的例子以不同的方式處理 countOfNewMessages 為 0 的情況。

9. ”棒棒“運算符

(1) 這種習(xí)慣看起來是什么樣的

將非布爾值轉(zhuǎn)換為布爾值。

  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) 應(yīng)該怎樣明

確檢查我們所關(guān)心的狀況。

  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) 為什么會有這種壞習(xí)慣

對某些人而言,理解 !! 就像是進(jìn)入 JavaScript 世界的入門儀式。它看起來簡短而簡潔,如果你對它已經(jīng)非常習(xí)慣了,就會知道它的含義。這是將任意值轉(zhuǎn)換為布爾值的便捷方式。尤其是在如果虛值之間沒有明確的語義界限時,例如 null、undefined 和 ''。

(4) 為什么不該這樣做

與很多編碼時的便捷方式一樣,使用 !! 實際上是混淆了代碼的真實含義。這使得新開發(fā)人員很難理解代碼,無論是對一般開發(fā)人員來說還是對 JavaScript 來說都是新手。也很容易引入細(xì)微的錯誤。在對“非布爾類型的值”進(jìn)行布爾檢查時 countOfNewMessages為 0 的問題在使用 !! 時仍然會存在。

10. != null

(1) 這種習(xí)慣看起來是什么樣的

棒棒運算符的小弟 ! = 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) 應(yīng)該怎樣

明確檢查我們所關(guān)心的狀況。

  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) 為什么會有這種壞習(xí)慣

如果你的代碼在 null 和 undefined 之間沒有明顯的區(qū)別,那么 != null 有助于簡化對這兩種可能性的檢查。

(4) 為什么不該這樣做

盡管 null 在 JavaScript早期很麻煩,但 TypeScript 處于 strict 模式時,它卻可以成為這種語言中寶貴的工具。一種常見模式是將 null 值定義為不存在的事物,將 undefined 定義為未知的事物,例如 user.firstName === null 可能意味著用戶實際上沒有名字,而 user.firstName === undefined 只是意味著我們尚未詢問該用戶(而 user.firstName === 的意思是字面意思是 '' 。

 

責(zé)任編輯:趙寧寧 來源: 前端先鋒
相關(guān)推薦

2022-09-11 15:02:21

JavaScriptTypeScript數(shù)據(jù)

2019-11-28 18:51:07

PythonPHP編程語言

2018-11-26 09:40:39

Python壞習(xí)慣編程語言

2018-10-17 11:20:55

SQL數(shù)據(jù)庫程序員

2012-05-22 00:16:47

2021-11-01 22:39:14

程序員專業(yè)技術(shù)

2009-07-21 14:32:02

IT人習(xí)慣

2020-12-15 16:44:48

代碼程序運行

2019-01-25 17:21:04

程序員壞習(xí)慣

2018-01-11 13:57:36

程序員技能開發(fā)者

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開發(fā)

2012-07-17 11:13:44

程序員

2024-01-07 13:25:32

Go編程代碼

2024-01-15 06:45:29

Go編程代碼

2009-07-20 14:02:49

66天習(xí)慣養(yǎng)成改正壞習(xí)慣

2013-07-24 14:17:48

點贊
收藏

51CTO技術(shù)棧公眾號