简体   繁体   English

使用枚举值作为接口中的键

[英]Use Enum values as a key in interface

I am struggling to create an interface that uses values from an Enum.我正在努力创建一个使用枚举值的接口。

enum TestEnum {
  'VAL1' = 'TEST1',
  'VAL2' = 'TEST2'
}

interface IMyInterface {
  [TestEnum[key in TestEnum]]: {
    // some code
  }
}

const objToType: IMyInterface = {
  TEST1: { / ** \ }
  TEST2: { / ** \ }
}

It throws an error它抛出一个错误

A computed property name in a type literal must refer to an expression whose type is a literal type or a 'unique symbol' type.类型文字中的计算属性名称必须引用其类型为文字类型或“唯一符号”类型的表达式。

What's the problem here?这里有什么问题?

I think the confusing bit is that [key in TestEnum] returns the "values" of the enum rather than the "keys" (if you want to iterate the keys you'd use [key in keyof TestEnum] ).我认为令人困惑的是[key in TestEnum]返回枚举的“值”而不是“键”(如果您想迭代您将使用的键[key in keyof TestEnum] )。

This is easy to do using a type declaration rather than an interface declaration:使用type声明而不是接口声明很容易做到这一点:

enum TestEnum {
  'VAL1' = 'TEST1',
  'VAL2' = 'TEST2'
}

type IMyInterface = {
  [key in TestEnum]: { /* */ }
}

const objToType: IMyInterface = {
  TEST1: { },
  TEST2: { }
}

Playground link 游乐场链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM