簡體   English   中英

打字稿:來自接口鍵的枚舉

[英]Typescript: Enum from Interface keys

我有一個界面:

interface ISomething {
  red: string;
  blue: string;
  green: string;
}

是否可以定義代表接口鍵的枚舉?

我想得到這樣的結果:

enum SomethingKeys {
   red = "red",
   blue= "blue",
   green= "green",
}

ps:我是ts的新手,如果問題不正確,請見諒。

您可以通過創建一個帶有枚舉鍵的對象來做其他事情:

enum SomethingKeys {
   red = "red",
   blue= "blue",
   green= "green",
}
type ISomething= Record<SomethingKeys, string>
const a: ISomething = {
    [SomethingKeys.blue]: 'blue',
    [SomethingKeys.red]: 'red',
    [SomethingKeys.green]: 'green',
}

但我認為你真正需要的不是 enum 而是聯合類型的鍵,你定義的keyof 考慮:

interface ISomething {
  red: string;
  blue: string;
  green: string;
}
type Keys = keyof ISomething; // "red" | "blue" | "green"

當您聲明自己是新手時,可以使用字符串文字聯合。 你不需要枚舉。

當您擁有Keys您也可以使用它們來創建其他類型

// new object with keys of the original one
type OtherTypeWithTheSameKeys = Record<Keys, number> // type with keys of type Keys
const a: OtherTypeWithTheSameKeys = {
  blue: 1,
  green: 2,
  red: 3
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM