寫TypeScript代碼的10種壞習慣,一不小心就被罰了500塊

作者:Daniel Bartholomae

翻譯:瘋狂的技術宅

原文鏈接:https://startup-cto.net/10-bad-typescript-habits-to-break-this-year/

近幾年 TypeScript 和 JavaScript 一直在穩步發展。我們在過去寫代碼時養成了一些習慣,而有些習慣卻沒有什麼意義。以下是我們都應該改正的 10 個壞習慣。

1.不使用 strict 模式

這種習慣看起來是什麼樣的

沒有用嚴格模式編寫 tsconfig.json。

{
  "compilerOptions": {
    "target": "ES2015",
    "module": "commonjs"
  }
}

應該怎樣

只需啓用 strict 模式即可:

{
  "compilerOptions": {
    "target": "ES2015",
    "module": "commonjs",
    "strict": true
  }
}

爲什麼會有這種壞習慣

在現有代碼庫中引入更嚴格的規則需要花費時間。

爲什麼不該這樣做

更嚴格的規則使將來維護代碼時更加容易,使你節省大量的時間。

2. 用 || 定義默認值

這種習慣看起來是什麼樣的

使用舊的 || 處理後備的默認值:

function createBlogPost (text: string, author: string, date?: Date) {
 return {
    text: text,
    author: author,
    date: date || new Date()
  }
}

應該怎樣

使用新的 ?? 運算符,或者在參數重定義默認值。

function createBlogPost (text: string, author: string, date: Date = new Date())
 return {
    text: text,
    author: author,
    date: date
  }
}

爲什麼會有這種壞習慣

?? 運算符是去年才引入的,當在長函數中使用值時,可能很難將其設置爲參數默認值。

爲什麼不該這樣做

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

3. 隨意使用 any 類型

這種習慣看起來是什麼樣的

當你不確定結構時,可以用 any 類型。

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

應該怎樣

把你代碼中任何一個使用 any 的地方都改爲 unknown

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

爲什麼會有這種壞習慣

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

爲什麼不該這樣做

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

4. val as SomeType

這種習慣看起來是什麼樣的

強行告訴編譯器無法推斷的類型。

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

應該怎樣

這正是 Type Guard 的用武之地。

function isArrayOfProducts (obj: unknown): obj is Product[] {
 return Array.isArray(obj) && obj.every(isProduct)
}

function isProduct (obj: unknown): obj is Product {
 return obj != null
    && typeof (obj as Product).id === 'string'
}

async function loadProducts(): Promise<Product[]> {
 const response = await fetch('https://api.mysite.com/products')
 const products: unknown = await response.json()
 if (!isArrayOfProducts(products)) {
 throw new TypeError('Received malformed products API response')
  }
 return products
}

爲什麼會有這種壞習慣

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

爲什麼不該這樣做

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

5. 測試中的 as any

這種習慣看起來是什麼樣的

編寫測試時創建不完整的用例。

interface User {
  id: string
  firstName: string
  lastName: string
  email: string
}

test('createEmailText returns text that greats the user by first name', () => {
 const user: User = {
    firstName: 'John'
  } as any
 
  expect(createEmailText(user)).toContain(user.firstName)
}

應該怎樣

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

interface User {
  id: string
  firstName: string
  lastName: string
  email: string
}

class MockUser implements User {
  id = 'id'
  firstName = 'John'
  lastName = 'Doe'
  email = '[email protected]'
}

test('createEmailText returns text that greats the user by first name', () => {
 const user = new MockUser()

  expect(createEmailText(user)).toContain(user.firstName)
}

爲什麼會有這種壞習慣

在給尚不具備廣泛測試覆蓋條件的代碼編寫測試時,通常會存在複雜的大數據結構,但要測試的特定功能僅需要其中的一部分。短期內不必關心其他屬性。

爲什麼不該這樣做

在某些情況下,被測代碼依賴於我們之前認爲不重要的屬性,然後需要更新針對該功能的所有測試。

6. 可選屬性

這種習慣看起來是什麼樣的

將屬性標記爲可選屬性,即便這些屬性有時不存在。

interface Product {
  id: string
  type: 'digital' | 'physical'
  weightInKg?: number
  sizeInMb?: number
}

應該怎樣

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

interface Product {
  id: string
  type: 'digital' | 'physical'
}

interface DigitalProduct extends Product {
  type: 'digital'
  sizeInMb: number
}

interface PhysicalProduct extends Product {
  type: 'physical'
  weightInKg: number
}

爲什麼會有這種壞習慣

將屬性標記爲可選而不是拆分類型更容易,並且產生的代碼更少。它還需要對正在構建的產品有更深入的瞭解,並且如果對產品的設計有所修改,可能會限制代碼的使用。

爲什麼不該這樣做

類型系統的最大好處是可以用編譯時檢查代替運行時檢查。通過更顯式的類型,能夠對可能不被注意的錯誤進行編譯時檢查,例如確保每個 DigitalProduct 都有一個 sizeInMb。

7. 用一個字母通行天下

這種習慣看起來是什麼樣的

用一個字母命名泛型

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

應該怎樣

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

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

爲什麼會有這種壞習慣

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

爲什麼不該這樣做

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

8. 對非布爾類型的值進行布爾檢查

這種習慣看起來是什麼樣的

通過直接將值傳給 if 語句來檢查是否定義了值。

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

應該怎樣

明確檢查我們所關心的狀況。

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

爲什麼會有這種壞習慣

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

爲什麼不該這樣做

也許我們應該考慮一下實際要檢查的內容。例如上面的例子以不同的方式處理 countOfNewMessages 爲 0 的情況。

9. ”棒棒“運算符

這種習慣看起來是什麼樣的

將非布爾值轉換爲布爾值。

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

應該怎樣

明確檢查我們所關心的狀況。

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

爲什麼會有這種壞習慣

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

爲什麼不該這樣做

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

10. != null

這種習慣看起來是什麼樣的

棒棒運算符的小弟 ! = null使我們能同時檢查 null 和 undefined。

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

應該怎樣

明確檢查我們所關心的狀況。

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

爲什麼會有這種壞習慣

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

爲什麼不該這樣做

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

 

點擊關注,第一時間瞭解華爲雲新鮮技術~

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章