Typescript函数将字符串枚举成员转换为枚举 [英] Typescript function to convert string enum member to enum

查看:1066
本文介绍了Typescript函数将字符串枚举成员转换为枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Typescript中编写如下内容:

I'd like to write something like this in Typescript:

export function stringToEnum<T>(enumObj: T, str: string): keyof T {
    return enumObj[str];
}

并按以下方式使用:

enum MyEnum {
  Foo
}

stringToEnum<MyEnum>(MyEnum, 'Foo');

它将返回的位置

MyEnum.Foo

上面的函数按预期工作...但是键入会引发错误。对于 stringToEnum< MyEnum>(MyEnum,'Foo'); 中的参数 MyEnum ,Typescript抱怨::

The function above works as expected... but the typings are throwing errors. For the parameter MyEnum in stringToEnum<MyEnum>(MyEnum, 'Foo');, Typescript complains tha:


类型'typeof MyEnum'的参数不能分配给
类型'MyEnum'的参数

Argument of type 'typeof MyEnum' is not assignable to parameter of type 'MyEnum'

这很有意义...不幸的是。关于如何解决这个问题的任何想法?

which makes sense... unfortunately. Any ideas on how I can get around this?

推荐答案

您可以在不编写函数的情况下完成所有操作:

You can do it all natively without having to write a function:

enum Color {
    red,
    green,
    blue
}

// Enum to string
const redString: string = Color[Color.red];
alert(redString);

// String to enum
const str = 'red';
const redEnum: Color = Color[str];
alert(redEnum);

或者您可以从中获得一些乐趣...

Or you can have some fun with it...

enum MyEnum {
  Foo,
  Bar
}

function stringToEnum<ET, T>(enumObj: ET, str: keyof ET): T{
    return enumObj[<string>str];
}

const val = stringToEnum<typeof MyEnum, MyEnum>(MyEnum, 'Foo');

// Detects that `foo` is a typo
const val2 = stringToEnum<typeof MyEnum, MyEnum>(MyEnum, 'foo');

这篇关于Typescript函数将字符串枚举成员转换为枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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