我有一個有兩個屬性的類
class X {
S1: string = "Hello"
S2: string = "World"
}
我想創建一個決議為字串值聯合的型別:"Hello" | "World"
我正在考慮使用類似 keyof 運算子的東西,唯一的問題是它產生string而不是實際值。
type V = X[keyof X]
uj5u.com熱心網友回復:
最符合人體工程學的方法是從欄位中洗掉顯式型別注釋并as const在值上使用斷言來保留文字型別:
class X {
S1 = "Hello" as const
S2 = "World" as const
}
type V = X[keyof X]

轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/510421.html
標籤:打字稿
