枚举作为参考在打字稿 [英] Enum as Parameter in typescript

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

问题描述

是否可以将参数的类型设置为枚举?像这样:

Isn't it possible to set the type of a parameter to an Enum? Like this:

private getRandomElementOfEnum(e : enum):string{
    var length:number = Object.keys(e).length;
    return e[Math.floor((Math.random() * length)+1)];
}

如果我这样做,Intellij将此代码标记为未知。并建议重命名变量,这是否有意义?

If I do that, Intellij mark this code as unknown. And suggest to rename the variable, does that make sense?

private getRandomElementOfEnum(e : any):string{
    var length:number = Object.keys(e).length;
    return e[Math.floor((Math.random() * length)+1)];
}

此代码工作正常。但是并不像优雅和代码般的。

This Code works fine. but isn't as elegant and code-convential.

将枚举定义为参数是否有可能或一些解决方法?

Is there a possibility or a little workaround to define an enum as a parameter?

编辑:

在学习了这些答案之后,我可以用这个定义的枚举集,这个类似enum1 | enum2 | enum3啊

After studying those answers, Can I do this also with ah set of defined enum, sth similar to enum1|enum2|enum3?

推荐答案

不可能确保参数是枚举,因为TS中的枚举不会从共同的祖先或接口继承。

It's not possible to ensure the parameter is an enum, because enumerations in TS don't inherit from a common ancestor or interface.

TypeScript带来静态分析。您的代码使用动态编程与 Object.keys e [dynamicKey] 。对于动态代码,类型任何都很方便。

TypeScript brings static analysis. Your code uses dynamic programming with Object.keys and e[dynamicKey]. For dynamic codes, the type any is convenient.

您的代码是错误的: length ()不存在, e [Math.floor((Math.random()* length)+1)] 返回一个字符串或一个整数,和枚举值可以手动设置 ...

Your code is buggy: length() doesn't exists, e[Math.floor((Math.random() * length)+1)] returns a string or an integer, and the enumeration values can be manually set…

这是一个建议:

function getRandomElementOfEnum<E>(e: any): E {
    var keys = Object.keys(e),
        index = Math.floor(Math.random() * keys.length),
        k = keys[index];
    if (typeof e[k] === 'number')
        return <any>e[k];
    return <any>parseInt(k, 10);
}

function display(a: Color) {
    console.log(a);
}

enum Color { Blue, Green };
display(getRandomElementOfEnum<Color>(Color));

理想情况下,参数类型 any 应该是替换为 typeof E ,但编译器(TS 1.5)无法理解此语法。

Ideally, the parameter type any should be replaced by typeof E but the compiler (TS 1.5) can't understand this syntax.

这篇关于枚举作为参考在打字稿的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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