【问题标题】:Typescript: Enum from Interface keys打字稿:来自接口键的枚举
【发布时间】:2020-05-09 21:32:51
【问题描述】:

我有一个界面:

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

是否可以定义 Enum 来表示接口中的键?

我想得到这样的结果:

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

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

【问题讨论】:

    标签: typescript enums interface


    【解决方案1】:

    您可以通过使用枚举键创建对象来做其他方式:

    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',
    }
    

    但我认为您真正需要的不是枚举,而是联合类型的键,您由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
    }
    

    【讨论】:

    • 感谢您的回答。是否可以通过接口键创建具有属性的对象?
    • 是的,给你加了一个样本
    • 谢谢,请指教,可以在某些函数中自动定义这样的对象吗?
    猜你喜欢
    • 1970-01-01
    • 2017-02-03
    • 2021-12-06
    • 2018-09-23
    • 2019-12-27
    • 2022-06-11
    • 1970-01-01
    • 2020-04-30
    • 1970-01-01
    相关资源
    最近更新 更多