10個寫TypeScript代碼的壞習(xí)慣
近幾年 TypeScript 和 JavaScript 一直在穩(wěn)步發(fā)展。我們在過去寫代碼時養(yǎng)成了一些習(xí)慣,而有些習(xí)慣卻沒有什么意義。以下是我們都應(yīng)該改正的 10 個壞習(xí)慣。
1. 不使用strict模式
(1) 這種習(xí)慣看起來是什么樣的
沒有用嚴(yán)格模式編寫 tsconfig.json。
- {
- "compilerOptions": {
- "target": "ES2015",
- "module": "commonjs"
- }
- }
(2) 應(yīng)該怎樣
只需啟用 strict 模式即可:
- {
- "compilerOptions": {
- "target": "ES2015",
- "module": "commonjs",
- "strict": true
- }
- }
(3) 為什么會有這種壞習(xí)慣
在現(xiàn)有代碼庫中引入更嚴(yán)格的規(guī)則需要花費時間。
(4) 為什么不該這樣做
更嚴(yán)格的規(guī)則使將來維護(hù)代碼時更加容易,使你節(jié)省大量的時間。
2. 用||定義默認(rèn)值
(1) 這種習(xí)慣看起來是什么樣的
使用舊的 || 處理后備的默認(rèn)值:
- function createBlogPost (text: string, author: string, date?: Date) {
- return {
- text: text,
- author: author,
- date: date || new Date()
- }
- }
(2) 應(yīng)該怎樣
使用新的 ?? 運算符,或者在參數(shù)重定義默認(rèn)值。
- function createBlogPost (text: string, author: string, date: Date = new Date())
- return {
- text: text,
- author: author,
- date: date
- }
- }
(3) 為什么會有這種壞習(xí)慣
?? 運算符是去年才引入的,當(dāng)在長函數(shù)中使用值時,可能很難將其設(shè)置為參數(shù)默認(rèn)值。
(4) 為什么不該這樣做
?? 與 || 不同,?? 僅針對 null 或 undefined,并不適用于所有虛值。
3. 隨意使用any類型
(1) 這種習(xí)慣看起來是什么樣的
當(dāng)你不確定結(jié)構(gòu)時,可以用 any 類型。
- async function loadProducts(): Promise<Product[]> {
- const response = await fetch('https://api.mysite.com/products')
- const products: any = await response.json()
- return products
- }
(2) 應(yīng)該怎樣
把你代碼中任何一個使用 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[]
- }
(3) 為什么會有這種壞習(xí)慣
any 是很方便的,因為它基本上禁用了所有的類型檢查。通常,甚至在官方提供的類型中都使用了 any。例如,TypeScript 團(tuán)隊將上面例子中的 response.json() 的類型設(shè)置為 Promise
(4) 為什么不該這樣做
它基本上禁用所有類型檢查。任何通過 any 進(jìn)來的東西將完全放棄所有類型檢查。這將會使錯誤很難被捕獲到。
4. val as SomeType
(1) 這種習(xí)慣看起來是什么樣的
強(qiáng)行告訴編譯器無法推斷的類型。
- async function loadProducts(): Promise<Product[]> {
- const response = await fetch('https://api.mysite.com/products')
- const products: unknown = await response.json()
- return products as Product[]
- }
(2) 應(yīng)該怎樣
這正是 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
- }
(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)建不完整的用例。
- 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)
- }
(2) 應(yīng)該怎樣
如果你需要模擬測試數(shù)據(jù),請將模擬邏輯移到要模擬的對象旁邊,并使其可重用。
- interface User {
- id: string
- firstName: string
- lastName: string
- email: string
- }
- class MockUser implements User {
- id = 'id'
- firstName = 'John'
- lastName = 'Doe'
- email = 'john@doe.com'
- }
- test('createEmailText returns text that greats the user by first name', () => {
- const user = new MockUser()
- 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)記為可選屬性,即便這些屬性有時不存在。
- interface Product {
- id: string
- type: 'digital' | 'physical'
- weightInKg?: number
- sizeInMb?: number
- }
(2) 應(yīng)該怎樣
明確哪些組合存在,哪些不存在。
- interface Product {
- id: string
- type: 'digital' | 'physical'
- }
- interface DigitalProduct extends Product {
- type: 'digital'
- sizeInMb: number
- }
- interface PhysicalProduct extends Product {
- type: 'physical'
- 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í)慣看起來是什么樣的
用一個字母命名泛型
- function head<T> (arr: T[]): T | undefined {
- return arr[0]
- }
(2) 應(yīng)該怎樣
提供完整的描述性類型名稱。
- function head<Element> (arr: Element[]): Element | undefined {
- 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 語句來檢查是否定義了值。
- function createNewMessagesResponse (countOfNewMessages?: number) {
- if (countOfNewMessages) {
- return `You have ${countOfNewMessages} new messages`
- }
- return 'Error: Could not retrieve number of new messages'
- }
(2) 應(yīng)該怎樣
明確檢查我們所關(guān)心的狀況。
- function createNewMessagesResponse (countOfNewMessages?: number) {
- if (countOfNewMessages !== undefined) {
- return `You have ${countOfNewMessages} new messages`
- }
- 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)換為布爾值。
- function createNewMessagesResponse (countOfNewMessages?: number) {
- if (!!countOfNewMessages) {
- return `You have ${countOfNewMessages} new messages`
- }
- return 'Error: Could not retrieve number of new messages'
- }
(2) 應(yīng)該怎樣明
確檢查我們所關(guān)心的狀況。
- function createNewMessagesResponse (countOfNewMessages?: number) {
- if (countOfNewMessages !== undefined) {
- return `You have ${countOfNewMessages} new messages`
- }
- 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。
- function createNewMessagesResponse (countOfNewMessages?: number) {
- if (countOfNewMessages != null) {
- return `You have ${countOfNewMessages} new messages`
- }
- return 'Error: Could not retrieve number of new messages'
- }
(2) 應(yīng)該怎樣
明確檢查我們所關(guān)心的狀況。
- function createNewMessagesResponse (countOfNewMessages?: number) {
- if (countOfNewMessages !== undefined) {
- return `You have ${countOfNewMessages} new messages`
- }
- 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 === 的意思是字面意思是 '' 。