typescript - 创建 ENUM(-like) 类型的对象值
问题描述
我有一个对象
const modalTypes = {
newPizza: 'NEW_PIZZA',
newCola: 'NEW_COLA',
newCustom: 'NEW_CUSTOM,
}
然后我有一个动作创建者,它采取的动作是modalTypes
' 价值观之一。
const showModal = (modalType: ModalType, body: BodyType) => {
// do something...
}
// e.g.
showModal('NEW_PIZZA', ...)
如何ModalType
获得NEW_PIZZA | NEW_COLA | NEW_CUSTOM
?
与此类似的东西,但对于价值观。
const Foo = { a: 'FOO', b: 'BAR', c: 'BAZ' };
type Abc = keyof typeof Foo
Abc = 'a' | 'b' | 'c'
// Desired = 'FOO' | 'BAR' | 'BAZ'
解决方案
正如@ExplosionPills 所说,在没有额外注释的情况下,值的类型是通用的,但是如果您可以添加注释,则可以:
const modalTypes = {
newPizza: 'NEW_PIZZA' as 'NEW_PIZZA',
newCola: 'NEW_COLA' as 'NEW_COLA',
newCustom: 'NEW_CUSTOM' as 'NEW_CUSTOM',
}
type ModalType = typeof modalTypes[keyof typeof modalTypes]
推荐阅读
- webpack - Webpack 相对 url(../images/example.png) 不适用于 node_modules 包
- java - 字符串生成器替换字符串中偶数索引处的元素
- spring-boot - 无法创建 Firestore Bean,BeanCreationException。java.lang.NoClassDefFoundError: com/google/api/gax/rpc/TransportChannelProvider
- ajax - 在 SelectOnemenu 上重置 JSF Primefaces 输入值
- nuxt.js - Vuex 整个状态分配
- c# - Botframework v4 在瀑布对话流之外恢复对话
- python - Pandas汇总价格并计算价格与数量数据的权重/权重,并按5个价格分组
- php - Foreach 循环仅在 api 中显示数组中的最后一项
- c# - 在 C# 中将 base64 图像与字符串分离的最佳方法
- java - .replace 没有更新变量值,导致错误写入输出文件