typescript - 有没有办法在对象的接口中使用字符串文字类型?
问题描述
我有一个类型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.
我应该如何在接口中正确使用字符串文字类型?
解决方案
在那里使用字符串文字很重要吗?带有字符串值的枚举是否不够:
enum Colors {
YELLOW = 'yellow',
RED = 'red',
ORANGE = 'orange',
}
interface ColorSetting {
id: string;
color: Colors;
}
这种方法的唯一缺点是如果你需要反向映射这个,打字稿不会自己做。
我自己倾向于不使用这样的文字,所以我不确定这是否有效,但试一试:
interface ColorSetting {
id: string;
color: Color;
}
基本上只需使用您声明的类型,删除 '[k in Color]' 位
推荐阅读
- webpack-dev-server - CRA - 如何代理除特定请求之外的所有请求?
- android - 使用 DrawerLayout 时工具栏的问题
- c# - 如何在 ASP.NET 框架中获取我当前的 URL
- sql - 执行 Select 语句时,单行子查询在 select 中返回多于一行
- sql - 检查 Chartio 过滤器是否有空字符串 SQL CASE 语句
- python - 具有多个约束的 Python 中的约束回归
- python - 测试期间的 Django 双重导入
- create-react-app - 错误:在 create-react-app 项目上运行 npm start 时找不到模块“p-map”
- mysql - 如何明智地设置结果日期
- excel - AdvancedFilter 行为不一致?