我有一些帶有指示其型別的靜態變數的類。我想基于這些靜態變數創建一個聯合型別
class Foo {
static typeId = 'i-am-foo';
}
class Bar {
static typeId = 'i-am-bar';
}
type MyUnionType = Foo.typeId | Bar.typeId;
TS游樂場
不幸的是,這是不可能的,我得到了錯誤
'Foo' 僅指一種型別,但在這里用作命名空間。
是否可以使用靜態變數進行型別定義?
uj5u.com熱心網友回復:
i-am-fooandi-am-bar是值,而不是型別,您正在嘗試訪問它們并結合起來創建一個聯合。要正確執行此操作,您需要使用typeof.
此外,使用正確的型別正確鍵入您的靜態值。如果您不指定:
static typeId :'i-am-foo'= 'i-am-foo';
的型別typeId是廣泛的型別string,兩種string型別的聯合都是string。
注意:另一種方法是:
static typeId = 'i-am-foo' as const;
as const將告訴 TS 嘗試找到最窄的型別。
您的代碼如下所示:
class Foo {
static typeId :'i-am-foo'= 'i-am-foo';
}
class Bar {
static typeId : 'i-am-bar' = 'i-am-bar';
}
type MyUnionType = typeof Foo.typeId | typeof Bar.typeId;
操場
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/529964.html
標籤:打字稿
