简体   繁体   English

有没有办法在 object 的接口中使用字符串字面量类型?

[英]Is there a way to use the string literal type in an interface of object?

I have a type Color ,我有一个类型Color

type Color = 'yellow' | 'red' | 'orange'

And I have an object which interface is ColorSetting .我有一个 object 接口是ColorSetting

interface ColorSetting {
  id: string
  yellow?: boolean
  red?: boolean
  orange?: boolean
}

I want to use the type Color to simplify interface ColorSetting .我想使用Color类型来简化界面ColorSetting

The code I simplified is below:我简化的代码如下:

interface ColorSetting {
  id: string
  [k in Color]?: boolean
}

But I got an error about A computed property name in an interface must refer to an expression whose type is a literal type or a 'unique symbol' type.但是我收到一个错误A computed property name in an interface must refer to an expression whose type is a literal type or a 'unique symbol' type.

How should I use the string literal type correctly in an interface?我应该如何在接口中正确使用字符串文字类型?

Is it important to use a string literal there?在那里使用字符串文字很重要吗? Would an enum with string values not suffice:带有字符串值的枚举是否不够:

enum Colors {
  YELLOW = 'yellow',
  RED = 'red',
  ORANGE = 'orange',
}

interface ColorSetting {
  id: string;
  color: Colors;
}

The only downside to this approach is if you would ever need to reverse map this, which typescript doesn't do itself.这种方法的唯一缺点是如果您需要反转 map 这个,typescript 不会自己做。

I tend not to use literals like this myself, so I'm not sure if this works, but give it a try:我自己倾向于不使用这样的文字,所以我不确定这是否有效,但试一试:

interface ColorSetting {
  id: string;
  color: Color;
}

Basically just use your type as you've declared it, drop the '[k in Color]' bit基本上只需使用您声明的类型,删除 '[k in Color]' 位

I have found a solution, which is useful for me.我找到了一个对我有用的解决方案。 This solution uses an Intersection Types .此解决方案使用Intersection Types

ColorSetting = {
   id: string
 } & {
   [k in Color]?: boolean
 }

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

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