简体   繁体   English

将枚举类型作为打字稿中的参数传递

[英]Passing enum type as parameter in typescript

I have a function:我有一个功能:

public doSomethingWithEnum(enumType) {
   // Iterate over enum keys with Object.keys(enumType)
}

And I can use it like so:我可以像这样使用它:

export enum MyEnum { SomeEnumValue = 'SomeEnumValue', SomeOtherValue = 'SomeOtherValue' }

doSomethingWithEnum(MyEnum);

That's fine, it works.没关系,它有效。 The problem is that I'd like a type on that parameter so I can pass it any enum.问题是我想要该参数的类型,以便我可以将任何枚举传递给它。 At the moment, it might aswell be :any which I think is far too open.目前,它也可能是:any我认为太开放了。

Is there any way of restricting/specifying the type of that parameter?有没有办法限制/指定该参数的类型?

What I've Tried我试过的

I know it's possible to restrict this by listing known types eg:我知道可以通过列出已知类型来限制这一点,例如:

doSomethingWithEnum(enumType: MyEnum | MyOtherEnum)

But I need it more scalable than that, I don't want to have to append a type every time a different consumer needs to call the service.但我需要它比这更具可扩展性,我不想每次不同的消费者需要调用服务时都必须附加一个类型。

Enums are basically objects with key/value pairs, where the value is either a string or a number.枚举基本上是具有键/值对的对象,其中值是字符串或数字。 So if you want to make a function that accepts literally any enum you can do:因此,如果您想创建一个可以接受任何枚举的函数,您可以执行以下操作:

enum Example {
    foo,
    bar
};

const doSomethingWithEnum = (en: Record<string, string | number>) => {
    Object.keys(en).forEach(key => console.log(key));
}

doSomethingWithEnum(Example);

This does mean that you could construct a non-enum object with strings/numbers as its keys and pass that in too.这确实意味着您可以构造一个以字符串/数字为键的非枚举对象并将其传入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM