简体   繁体   English

Typescript:可以使用enum作为函数参数类型吗?

[英]Typescript: is it ok to use enum as function parameter type?

Simple question, yet I have a doubt and couldn't find the answer. 简单的问题,但我有一个疑问,找不到答案。

Suppose you have this enum: 假设您有以下枚举:

export enum fooEnum {
    Foo = 'foo',
    Bar = 'bar'
}

Then would it be ok to type my function parameters this way? 那么可以这样输入我的函数参数吗? Meaning 'I expect to receive a string 'foo' or 'bar' as parameter and expect to return 'foo' or 'bar' 含义“我希望接收字符串'foo'或'bar'作为参数,并希望返回'foo'或'bar'

function doStuff(myParam: FooEnum): FooEnum {
    return myParam;
};

It is perfectly fine to use an enum as parameter. 最好使用enum作为参数。

The only thing that you might want to consider (but in most cases negligible), is that an enum will be included in the generated JavaScript . 您可能要考虑的唯一事情(但在大多数情况下可以忽略不计)是在生成的JavaScript中将包含一个enum

export enum fooEnum {
    Foo = 'foo',
    Bar = 'bar'
}

Will generate the following JavaScript code (or similar): 将生成以下JavaScript代码(或类似代码):

var fooEnum;
(function (fooEnum) {
    fooEnum["Foo"] = "foo";
    fooEnum["Bar"] = "bar";
})(fooEnum || (fooEnum = {}));

As an alternative you could use a String Literal type, which will not be included in the generated code. 或者,您可以使用String Literal类型,该类型将不包含在生成的代码中。

export type fooType = 'foo' | 'bar';

EDIT - Thanks to Aleksey L. 编辑 -感谢Aleksey L.

You can also define a const enum , which is also not included in the generated code. 您还可以定义一个const enum ,它也不包含在生成的代码中。

export const enum fooEnum {
    Foo = 'foo',
    Bar = 'bar'
}

And when used 而当使用

var bar = fooEnum.Bar;

the following code will be generated as 以下代码将生成为

var b = 'bar';

const enum VS string literal type const枚举VS字符串文字类型

With the const enum approach it comes down to just personal preference whether you find 使用const enum方法,无论您是否发现,都归结为个人喜好

doStuff(fooEnum.Bar);

or string literal types string literal类型

doStuff('bar');

more readable. 更具可读性。 The generated result will be the same in both cases. 在两种情况下,生成的结果都是相同的。

An enum is just like any other type it can be used as a parameter and also used as a return type. enum就像任何其他类型一样,可以用作参数,也可以用作返回类型。 So yes that syntax would work fine. 是的,该语法可以正常工作。

I do not know why you would need to pass in an Enum value and then return a different Enum value but none the less you can do what you are doing and it is correct in TypeScript. 我不知道为什么您需要传递一个Enum值然后返回一个不同的Enum值,但是您仍然可以做您正在做的事情,并且在TypeScript中是正确的。

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

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