這篇文章主要介紹了TypeScript編寫代碼時應改正的壞習慣有哪些,具有一定借鑒價值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。
strict 模式沒有用嚴格模式編寫 tsconfig.json。
{
"compilerOptions": {
"target": "ES2015",
"module": "commonjs"
}
}只需啟用 strict 模式即可:
{
"compilerOptions": {
"target": "ES2015",
"module": "commonjs",
"strict": true
}
}在現有代碼庫中引入更嚴格的規則需要花費時間。
更嚴格的規則使將來維護代碼時更加容易,使你節省大量的時間。
|| 定義默認值使用舊的 || 處理后備的默認值:
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,并不適用于所有虛值。
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 進來的東西將完全放棄所有類型檢查。這將會使錯誤很難被捕獲到。
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 會確保所有檢查都是明確的。
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 = 'john@doe.com'
}
test('createEmailText returns text that greats the user by first name', () => {
const user = new MockUser()
expect(createEmailText(user)).toContain(user.firstName)
}在給尚不具備廣泛測試覆蓋條件的代碼編寫測試時,通常會存在復雜的大數據結構,但要測試的特定功能僅需要其中的一部分。短期內不必關心其他屬性。
在某些情況下,被測代碼依賴于我們之前認為不重要的屬性,然后需要更新針對該功能的所有測試。
將屬性標記為可選屬性,即便這些屬性有時不存在。
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。
用一個字母命名泛型
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'。同樣,一個字母的變量名通常會令人費解,因為不看聲明就很難理解它們的含義。
通過直接將值傳給 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 的情況。
將非布爾值轉換為布爾值。
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 的問題在使用 !! 時仍然會存在。
!= 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 === 的意思是字面意思是 '' 。
感謝你能夠認真閱讀完這篇文章,希望小編分享的“TypeScript編寫代碼時應改正的壞習慣有哪些”這篇文章對大家有幫助,同時也希望大家多多支持億速云,關注億速云行業資訊頻道,更多相關知識等著你來學習!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。