如何在 TypeScript 中将字符串转换为枚举?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17380845/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 01:05:58  来源:igfitidea点击:

How do I convert a string to enum in TypeScript?

typescript

提问by Amitabh

I have defined the following enum in TypeScript:

我在 TypeScript 中定义了以下枚举:

enum Color{
    Red, Green
}

Now in my function I receive color as a string. I have tried the following code:

现在在我的函数中,我将颜色作为字符串接收。我尝试了以下代码:

var green= "Green";
var color : Color = <Color>green; // Error: can't convert string to enum

How can I convert that value to an enum?

如何将该值转换为枚举?

回答by basarat

Enums in TypeScript 0.9 are string+number based. You should not need type assertion for simple conversions:

TypeScript 0.9 中的枚举是基于字符串+数字的。对于简单的转换,您不应该需要类型断言:

enum Color{
    Red, Green
}

// To String
 var green: string = Color[Color.Green];

// To Enum / number
var color : Color = Color[green];

Try it online

网上试试

I have documention about this and other Enum patterns in my OSS book : https://basarat.gitbook.io/typescript/type-system/enums

我在我的 OSS 书中有关于这个和其他枚举模式的文档:https: //basarat.gitbook.io/typescript/type-system/enums

回答by Victor

As of Typescript 2.1 string keys in enums are strongly typed. keyof typeofis used to get info about available string keys (1):

从 Typescript 2.1 开始,枚举中的字符串键是强类型的。keyof typeof用于获取有关可用字符串键 ( 1) 的信息:

enum Color{
    Red, Green
}

let typedColor: Color = Color.Green;
let typedColorString: keyof typeof Color = "Green";

// Error "Black is not assignable ..." (indexing using Color["Black"] will return undefined runtime)
typedColorString = "Black";

// Error "Type 'string' is not assignable ..." (indexing works runtime)
let letColorString = "Red";
typedColorString = letColorString;

// Works fine
typedColorString = "Red";

// Works fine
const constColorString = "Red";
typedColorString = constColorString

// Works fine (thanks @SergeyT)
let letColorString = "Red";
typedColorString = letColorString as keyof typeof Color;

typedColor = Color[typedColorString];

https://www.typescriptlang.org/docs/handbook/advanced-types.html#index-types

https://www.typescriptlang.org/docs/handbook/advanced-types.html#index-types

回答by Artru

If you are sure that an input string has an exact match with Color enum then use:

如果您确定输入字符串与 Color 枚举完全匹配,请使用:

const color: Color = (<any>Color)["Red"];

In the case where an input string may not match Enum, use:

如果输入字符串可能与 Enum 不匹配,请使用:

const mayBeColor: Color | undefined = (<any>Color)["WrongInput"];
if (mayBeColor !== undefined){
     // TypeScript will understand that mayBeColor is of type Color here
}

Playground

操场



If we do not cast enumto <any>type then TypeScript will show the error:

如果我们不强制转换enum<any>类型,那么 TypeScript 将显示错误:

Element implicitly has 'any' type because index expression is not of type 'number'.

元素隐式具有“any”类型,因为索引表达式不是“number”类型。

It means that by default the TypeScript Enum type works with number indexes, i.e. let c = Color[0], but not with string indexes like let c = Color["string"]. This is a known restriction by the Microsoft team for the more general issue Object string indexes.

这意味着默认情况下,TypeScript Enum 类型适用于数字索引,即 let c = Color[0],但不适用于像let c = Color["string"]. 这是 Microsoft 团队针对更普遍的问题Object string index的已知限制。

回答by Jonas

enum Color{
    Red, Green
}

// To String
 var green: string = Color[Color.Green];

// To Enum / number
var color : Color = Color[green as keyof typeof Color]; //Works with --noImplicitAny

This example works with --noImplicitAnyin TypeScript

此示例适用--noImplicitAny于 TypeScript

Sources:
https://github.com/Microsoft/TypeScript/issues/13775#issuecomment-276381229https://www.typescriptlang.org/docs/handbook/advanced-types.html#index-types

来源:
https: //github.com/Microsoft/TypeScript/issues/13775#issuecomment-276381229 https://www.typescriptlang.org/docs/handbook/advanced-types.html#index-types

回答by Sly_cardinal

This note relates to basarat's answer, not the original question.

此注释与 basarat 的答案有关,而不是原始问题。

I had an odd issue in my own project where the compiler was giving an error roughly equivalent to "cannot convert string to Color" using the equivalent of this code:

我在自己的项目中遇到了一个奇怪的问题,编译器使用以下代码给出了一个大致相当于“无法将字符串转换为颜色”的错误:

var colorId = myOtherObject.colorId; // value "Green";
var color: Color = <Color>Color[colorId]; // TSC error here: Cannot convert string to Color.

I found that the compiler type inferencing was getting confused and it thought that colorIdwas an enum value and not an ID. To fix the problem I had to cast the ID as a string:

我发现编译器类型推断变得混乱,它认为这colorId是一个枚举值而不是一个 ID。为了解决这个问题,我必须将 ID 转换为字符串:

var colorId = <string>myOtherObject.colorId; // Force string value here
var color: Color = Color[colorId]; // Fixes lookup here.

I'm not sure what caused the issue but I'll leave this note here in case anyone runs into the same problem I did.

我不确定是什么导致了这个问题,但我会在这里留下这张便条,以防有人遇到和我一样的问题。

回答by Amitabh

I got it working using the following code.

我使用以下代码让它工作。

var green= "Green";
var color : Color= <Color>Color[green];

回答by alexania

If you provide string values to your enum, a straight cast works just fine.

如果您为枚举提供字符串值,则直接转换就可以了。

enum Color {
  Green = "Green",
  Red = "Red"
}

const color = "Green";
const colorEnum = color as Color;

回答by Nick N.

Given you use typescript: Many of the solutions above might not work or are overly complex.

鉴于您使用打字稿:上述许多解决方案可能不起作用或过于复杂。

Situation: The strings are not the same as the enum values (casing differs)

情况:字符串与枚举值不同(大小写不同)

enum Color {
  Green = "green",
  Red = "red"
}

Just use:

只需使用:

const color = "green" as Color

回答by Chris

I also ran into the same compiler error. Just a slight shorter variation of Sly_cardinal's approach.

我也遇到了同样的编译器错误。只是 Sly_cardinal 方法的一个更短的变体。

var color: Color = Color[<string>colorId];

回答by Luka

If the TypeScript compiler knows that the type of variable is string then this works:

如果 TypeScript 编译器知道变量的类型是字符串,那么这可以工作:

let colorName : string = "Green";
let color : Color = Color[colorName];

Otherwise you should explicitly convert it to a string (to avoid compiler warnings):

否则,您应该将其显式转换为字符串(以避免编译器警告):

let colorName : any = "Green";
let color : Color = Color["" + colorName];

At runtime both solutions will work.

在运行时,两种解决方案都将起作用。