不,an enum 在 TypeScript 中只能接受字符串或数值:
enum Stores {
STOREA = "amazon",
STOREB = "walmart"
}
但您可能不需要enum 来获得相同或相似的功能,具体取决于您的用例。如果我想将Stores 变成具有尽可能像enum 的对象值的东西,我会这样写:
const Stores = {
STOREA: { label: "Amazon", value: "amazon" },
STOREB: { label: "Walmart", value: "walmart" }
} as const;
type Stores = typeof Stores[keyof typeof Stores];
namespace Stores {
export type STOREA = typeof Stores.STOREA;
export type STOREB = typeof Stores.STOREB;
}
这里有三个东西叫Stores:
- 运行时存在的对象,具有键
STOREA 和 STOREB 以及对象值;
- 对应于union对象值
Stores对象内的类型;和
- 一个暴露自己类型的命名空间,因此
Stores.STOREA 类型是值Stores.STOREA 的类型,Stores.STOREB 类型是值Stores.STOREB 的类型。
有了这些,你基本上可以做任何真正的enum 会为你做的事情:
interface Foo {
store: Stores; // using the type here
}
interface AmazonFoo extends Foo {
store: Stores.STOREA; // using the namespace here
}
const foo: Foo = { store: Stores.STOREB }; // using the value here
const amFoo: AmazonFoo = { store: Stores.STOREA }; // using the value here
您可以验证这些用法是否适用于 Stores 的两个版本。当然,您的实际用例很可能不需要所有这些功能,在这种情况下,您只能包含您关心的那些。我的猜测是您绝对需要 const Stores = ... 对象,并且可能会使用 type Stores = .... 类型,但如果 namespace Stores { ... } 是必要的,我会有点惊讶。但同样,这取决于用例。
Playground link to code