首页 > 解决方案 > 有没有办法在对象的接口中使用字符串文字类型?

问题描述

我有一个类型Color

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

我有一个接口是的对象ColorSetting

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

我想使用类型Color来简化界面ColorSetting

我简化的代码如下:

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

但我有一个错误A computed property name in an interface must refer to an expression whose type is a literal type or a 'unique symbol' type.

我应该如何在接口中正确使用字符串文字类型?

标签: typescripttypescript-typings

解决方案


在那里使用字符串文字很重要吗?带有字符串值的枚举是否不够:

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

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

这种方法的唯一缺点是如果你需要反向映射这个,打字稿不会自己做。

我自己倾向于不使用这样的文字,所以我不确定这是否有效,但试一试:

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

基本上只需使用您声明的类型,删除 '[k in Color]' 位


推荐阅读