Typescript:接口键的枚举

Use*_*013 6 enums interface typescript

我有一个界面:

interface ISomething {
  red: string;
  blue: string;
  green: string;
}
Run Code Online (Sandbox Code Playgroud)

是否可以定义代表接口中的键的枚举?

我想得到这样的结果:

enum SomethingKeys {
   red = "red",
   blue= "blue",
   green= "green",
}
Run Code Online (Sandbox Code Playgroud)

ps:我是ts新手,如果问题不正确,请抱歉。

Mac*_*ora 4

您可以通过创建带有枚举键的对象来实现其他方法:

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',
}
Run Code Online (Sandbox Code Playgroud)

但我认为你真正需要的不是枚举而是联合类型的键,你定义的keyof。考虑:

interface ISomething {
  red: string;
  blue: string;
  green: string;
}
type Keys = keyof ISomething; // "red" | "blue" | "green"
Run Code Online (Sandbox Code Playgroud)

当您声明自己是新手时,可以使用字符串文字联合。你不需要枚举。

当你拥有时,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
}
Run Code Online (Sandbox Code Playgroud)