Typescript函数将字符串枚举成员转换为枚举

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');