我正在嘗試創建一個可用于定義另一種型別的類屬性:
class TypeOne {
public static readonly key: string = 'key';
}
class TypeTwo { public [TypeOne.key]: TypeOne }
但它顯示了這個錯誤:
類屬性宣告中的計算屬性名稱必須具有簡單的文字型別或“唯一符號”
它適用于列舉的常量值:
enum TypeThree {
key = 'key'
}
class TypeFour { public [TypeThree.key]: TypeThree }
有沒有辦法在類上設定一個常量值,以便編譯器可以接受它作為不可變鍵并理解欄位名稱?
uj5u.com熱心網友回復:
擺脫string注釋:
class TypeOne {
public static readonly key = 'key';
}
class TypeTwo { public [TypeOne.key]: TypeOne }
TS 需要屬性名稱的文字型別,字串太寬泛。
uj5u.com熱心網友回復:
您可以簡單地定義TypeOne為:
class TypeOne {
public static readonly key = 'key'; // Remove the string annotation
}
這使得key常量的值是文字字串'key',因為這是編譯器不會抱怨的唯一值
操場
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/451266.html
標籤:javascript 打字稿
上一篇:Javascript中的簡單for回圈可以避免復制時陣列的突變嗎
下一篇:Uncaught(inpromise)TypeError:Cannotreadpropertiesofundefined(reading'emailAddress')
