如果您愿意,您可以执行以下操作:
创建一个函数,要求其输入只有string
- 有价值的属性:
const enforceStringEnum = <E extends Record<keyof E, string>>(e: E) => {};
然后,声明Foo
如预期的:
enum Foo {
Bar,
Baz = 'Baz'
}
并调用该函数Foo
作为其输入:
enforceStringEnum(Foo); // error!
// Type 'Foo.Bar' is not assignable to type 'string'.
这会给你一个错误,并显示一条消息:Foo.Bar
,您可以返回并修复以消除错误。
是的,您收到的错误不是本地的Foo
声明,但它确实允许您保留Foo
as an enum
而不是使用其他语言结构。是的,enforceStringEnum()
在运行时有(非常小的)影响。如果你想完全没有运行时工件,这是可能的,但(在我看来)有点丑陋:
type EnforceStringEnum<E extends Record<keyof E, string>> = true;
enum Foo {
Bar,
Baz = 'Baz'
}
declare var fooWitness: EnforceStringEnum<typeof Foo>; // error!
// Type 'Foo.Bar' is not assignable to type 'string'.
但它的工作原理是一样的。
编辑:或者,正如@estus提到的,您可以使用类型别名而不是变量声明:
type FooWitness = EnforceStringEnum<typeof Foo>; // error!
// Type 'Foo.Bar' is not assignable to type 'string'.
希望有帮助。祝你好运!