指定枚举类型 [英] Specify enum type

查看:78
本文介绍了指定枚举类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有枚举:

enum Foo {
    Bar, // should cause type error
    Baz = 'Baz'
}

是否可以指定类型以使其成为字符串-only枚举?

Can a type be specified for it to make it string-only enum?

推荐答案

如果需要,可以执行以下操作:

You can do the following, if you want:

制作一个函数,要求其输入仅具有 string 值的属性:

Make a function which requires its input to have only string-valued properties:

const enforceStringEnum = <E extends Record<keyof E, string>>(e: E) => {};

然后,根据需要声明 Foo

enum Foo {
  Bar, 
  Baz = 'Baz'
}

然后调用 Foo 作为输入的函数:

And call the function with Foo as its input:

enforceStringEnum(Foo); // error!
// Type 'Foo.Bar' is not assignable to type 'string'.

这会给您一个错误,并提示有关 Foo.Bar ,您可以返回并修复以消除错误。

This will give you an error with a message about Foo.Bar, which you can go back and fix to remove the error.

是的,您得到的错误不是 Foo 声明,但它确实允许您将 Foo 保留为枚举使用其他语言结构。是的, enforceStringEnum()在运行时具有(非常小的)效果。如果您根本不希望有任何运行时工件,则有可能,但是(在我看来)有点难看:

Yes, the error you get isn't local to the Foo declaration, but it does allow you to keep Foo as an enum instead of using some other language structure. And yes, enforceStringEnum() has a (very small) effect at runtime. If you want to have no runtime artifacts at all, it's possible, but (in my opinion) a bit uglier:

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'.

但是它的工作方式相同。

But it works the same way.

编辑:或者,如@estus所述,您可以使用类型别名而不是变量声明:

Or, as @estus mentions, you could use a type alias instead of a variable declaration:

type FooWitness = EnforceStringEnum<typeof Foo>; // error!
// Type 'Foo.Bar' is not assignable to type 'string'.

希望有帮助。祝你好运!

Hope that helps. Good luck!

这篇关于指定枚举类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆