首页 > 解决方案 > 创建 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'

标签: typescripttypescript-typings

解决方案


正如@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]

推荐阅读