AS Const 五種使用技巧,你知道多少?
在 TypeScript 中,as const 是一種類型斷言,它將變量標(biāo)記為 “常量”。使用 as const 可以告訴 TypeScript 編譯器,某個(gè)對(duì)象的所有屬性都是只讀的,并且它們的類型是字面量類型,而不是更通用的類型,比如 string 或 number 類型。接下來(lái),我將介紹 TypeScript 中 as const 類型斷言的 5 個(gè)使用技巧。
1.確保對(duì)象的屬性不可變
在下面代碼中,雖然你使用 const 關(guān)鍵字來(lái)定義 DEFAULT_SERVER_CONFIG 常量。但你仍然可以修改該對(duì)象的屬性。
const DEFAULT_SERVER_CONFIG = {
host: "localhost",
port: 8080
}
DEFAULT_SERVER_CONFIG.port = 9090
console.log(`Server Host: ${DEFAULT_SERVER_CONFIG.port}`)
// "Server Host: 9090"
如果你希望該對(duì)象的屬性,是只讀的不允許修改,那么你可以使用 as const
類型斷言。
const DEFAULT_SERVER_CONFIG = {
host: "localhost",
port: 8080
} as const
之后,當(dāng)你嘗試修改 port 屬性時(shí),TypeScript 編譯器就會(huì)提示以下錯(cuò)誤信息:
as const 類型斷言,除了支持普通對(duì)象之外,還支持嵌套對(duì)象:
const DEFAULT_CONFIG = {
server: {
host: "localhost",
port: 8080
},
database: {
user: "root",
password: "root"
}
} as const
2.確保數(shù)組或元組不可變
在工作中,數(shù)組是一種常見(jiàn)的數(shù)組結(jié)構(gòu)。使用 as const 類型斷言,我們可以讓數(shù)組變成只讀。
const RGB_COLORS = ["red", "green", "blue"] as const
使用了 as const 類型斷言之后,RGB_COLORS 常量的類型被推斷為 readonly ["red", "green", "blue"] 類型。之后,當(dāng)你往 RGB_COLORS 數(shù)組添加新的顏色時(shí),TypeScript 編譯器就會(huì)提示以下錯(cuò)誤信息:
除了數(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)
3.常量枚舉的替代方案
在下面代碼中,我們使用 enum 關(guān)鍵字定義了 Colors 枚舉類型。
const enum Colors {
Red = 'RED',
Green = 'GREEN',
Blue = 'BLUE',
}
let color: Colors = Colors.Red; // Ok
color = Colors.Green // Ok
除了使用枚舉類型之外,利用 as const 類型斷言,你也可以實(shí)現(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'; // Ok
color = 'GREEN'; // Ok
4.讓類型推斷更精準(zhǔn)
在下面代碼中,red 變量的類型被推斷為 string 類型。
const RGB_COLORS = ["red", "green", "blue"];
let red = RGB_COLORS[0] // string
在某些場(chǎng)合中,你可能希望獲取更精確的類型,比如對(duì)應(yīng)的字面量類型,這時(shí)你就可以使用 as const 類型斷言:
const RGB_COLORS = ["red", "green", "blue"] as const;
let red = RGB_COLORS[0] // "red"
5.賦值時(shí)縮窄變量的類型
在下面代碼中,使用 const 關(guān)鍵字定義的常量,它的類型會(huì)被推斷為更精確的類型。
let color1 = "Red" // let color1: string
const color2 = "Red" // const color2: "Red"
利用 as const 類型斷言,我們也可以讓 let 關(guān)鍵字定義的變量對(duì)應(yīng)的類型更精準(zhǔn):
let color3 = "Red" as const // let color3: "Red"
當(dāng)然,在實(shí)際工作中,如果明確定義常量,那么推薦直接使用 const 關(guān)鍵字來(lái)定義。