在 TypeScript 中,as const 是一種類型斷言,它將變量標記為 “常量”。使用 as const 可以告訴 TypeScript 編譯器,某個對象的所有屬性都是只讀的,并且它們的類型是字面量類型,而不是更通用的類型,比如 string 或 number 類型。接下來,我將介紹 TypeScript 中 as const 類型斷言的 5 個使用技巧。
在下面代碼中,雖然你使用 const 關鍵字來定義 DEFAULT_SERVER_CONFIG 常量。但你仍然可以修改該對象的屬性。
const DEFAULT_SERVER_CONFIG = { host: "localhost", port: 8080}DEFAULT_SERVER_CONFIG.port = 9090console.log(`Server Host: ${DEFAULT_SERVER_CONFIG.port}`)// "Server Host: 9090"
如果你希望該對象的屬性,是只讀的不允許修改,那么你可以使用 as const
類型斷言。
const DEFAULT_SERVER_CONFIG = { host: "localhost", port: 8080} as const
之后,當你嘗試修改 port 屬性時,TypeScript 編譯器就會提示以下錯誤信息:
as const 類型斷言,除了支持普通對象之外,還支持嵌套對象:
const DEFAULT_CONFIG = { server: { host: "localhost", port: 8080 }, database: { user: "root", password: "root" }} as const
在工作中,數(shù)組是一種常見的數(shù)組結(jié)構(gòu)。使用 as const 類型斷言,我們可以讓數(shù)組變成只讀。
const RGB_COLORS = ["red", "green", "blue"] as const
使用了 as const 類型斷言之后,RGB_COLORS 常量的類型被推斷為 readonly ["red", "green", "blue"] 類型。之后,當你往 RGB_COLORS 數(shù)組添加新的顏色時,TypeScript 編譯器就會提示以下錯誤信息:
除了數(shù)組之外,你也可以在元組上使用 as const 類型斷言:
const person = ['kakuqo', 30, true] as const;person[0] = 'semlinker' // Error// Cannot assign to '0' because it is a read-only property.(2540)
在下面代碼中,我們使用 enum 關鍵字定義了 Colors 枚舉類型。
const enum Colors { Red = 'RED', Green = 'GREEN', Blue = 'BLUE',}let color: Colors = Colors.Red; // Okcolor = Colors.Green // Ok
除了使用枚舉類型之外,利用 as const 類型斷言,你也可以實現(xiàn)類似的功能:
const Colors = { Red: 'RED', Green: 'GREEN', Blue: 'BLUE',} as const;type ColorKeys = keyof typeof Colors;type ColorValues = typeof Colors[ColorKeys]let color: ColorValues = 'RED'; // Okcolor = 'GREEN'; // Ok
在下面代碼中,red 變量的類型被推斷為 string 類型。
const RGB_COLORS = ["red", "green", "blue"];let red = RGB_COLORS[0] // string
在某些場合中,你可能希望獲取更精確的類型,比如對應的字面量類型,這時你就可以使用 as const 類型斷言:
const RGB_COLORS = ["red", "green", "blue"] as const;let red = RGB_COLORS[0] // "red"
在下面代碼中,使用 const 關鍵字定義的常量,它的類型會被推斷為更精確的類型。
let color1 = "Red" // let color1: stringconst color2 = "Red" // const color2: "Red"
利用 as const 類型斷言,我們也可以讓 let 關鍵字定義的變量對應的類型更精準:
let color3 = "Red" as const // let color3: "Red"
當然,在實際工作中,如果明確定義常量,那么推薦直接使用 const 關鍵字來定義。
本文鏈接:http://www.www897cc.com/showinfo-26-77984-0.htmlAS Const 五種使用技巧,你知道多少?
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權(quán)等問題請及時與本網(wǎng)聯(lián)系,我們將在第一時間刪除處理。郵件:2376512515@qq.com
上一篇: 如何編寫高性能的Java代碼