简体   繁体   English

在TypeScript中从DOM属性转换为枚举

[英]Converting from DOM property to enum in TypeScript

I've got a enum like this: 我有一个像这样的枚举:

enum Steps {
    Step1,
    Step2,
    ...
}

I've tried to use it in a few different ways: 我试图以几种不同的方式使用它:

var cur_step : Steps = Steps[$(this).prop('data-step').toString()]; // compiler error
var str : string = $(this).prop('data-step').toString(); // no error
var cur_step : Steps = Steps[$(this).attr('data-step')];
var cur_step : Steps = Steps[String($(this).prop('data-step'))];
var cur_step : Steps = Steps[<string>$(this).prop('data-step')];

The first conversion from property to enum gives me a compiler error: 从属性到枚举的第一次转换给了我一个编译器错误:

Cannot convert 'string' to '{ Step1: Steps; 无法将'string'转换为'{Step1:Steps; Step2: Steps; 第二步: [x: number]: string; [x:数字]:字符串; }': Type 'String' is missing property 'Step1' from type '{ Step1: Steps; }':类型'String'缺少类型'{{Step1:Steps; Step2: Steps; 第二步: [x: number]: string; [x:数字]:字符串; }'. }'。

Why doesn't the first method work? 为什么第一种方法不起作用? toString() returns a base type of string for all instances of the method in lib.d.ts . toString()返回lib.d.ts方法的所有实例的字符串的基本类型。

Summary : Calling toString() on a variable of type any doesn't return a string. 摘要 :对any类型的变量调用toString()不会返回字符串。 You can cast instead using <string> . 您可以改为使用<string>进行<string> Full details below. 完整细节如下。

Conversion from string to enum is as you describe - here is an example that definitely works... 从字符串到枚举的转换正如您所描述的-这是一个绝对有效的示例...

enum Steps {
    Step1,
    Step2,
    Step3
}

var propValue = 'Step3';

var currentStep: Steps = Steps[propValue];

See this running 看到此运行

The compiler allows any property or function to be called on an any type (prop returns any in your case) and it doesn't infer the outcome. 编译器允许任何财产或功能上被称为any类型(道具返回any在你的情况下),它并不能推断结果。 So toString() in this instance is not assumed to be the real version that returns a string. 因此,在这种情况下, toString()不假定为返回字符串的真实版本。 Here is an example using your code: 这是使用您的代码的示例:

var x = $(this).prop('data-step').toString(); // x is any

And a short version of the example to prove the point: 并以该示例的简短版本证明了这一点:

var d: any;
d = 'test';
var e = d.toString(); // e is any

So to get around this with your example in a single line, you can use: 因此,为使示例在一行中得到解决,可以使用:

var currentStep: Steps = Steps[<string>$(this).prop('data-step')];

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

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