我有一个对象
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'
答案 0 :(得分:1)
就像@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]
答案 1 :(得分:1)
您可以使用npm install typescript@next
断言在3.4中进行操作而无需额外的断言(尚未发布,请使用as const
进行尝试,请参见PR。
const modalTypes = {
newPizza: 'NEW_PIZZA',
newCola: 'NEW_COLA',
newCustom: 'NEW_CUSTOM',
} as const
type ModalType = typeof modalTypes[keyof typeof modalTypes]
在3.4以下,我仍然不会走显式的断言路线,我宁愿使用一个辅助函数来推断正确的类型,它可以是IIFE:
const modalTypes = (<V extends string, T extends Record<string, V>>(o:T) => o)({
newPizza: 'NEW_PIZZA',
newCola: 'NEW_COLA',
newCustom: 'NEW_CUSTOM',
})
type ModalType = typeof modalTypes[keyof typeof modalTypes]
答案 2 :(得分:1)
如果ModalType是字符串常量的集合,则需要使用Enum代替这样的对象:
enum ModalType {
newPizza = "NEW_PIZZA",
newCola = "NEW_COLA",
newCustom = "NEW_CUSTOM",
}
const showModal = (modalType: ModalType[keyof ModalType]) => {
// do something...
};
showModal("NEW_PIZZA");