简体   繁体   中英

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; Step2: Steps; [x: number]: string; }': Type 'String' is missing property 'Step1' from type '{ Step1: Steps; Step2: Steps; [x: number]: string; }'.

Why doesn't the first method work? toString() returns a base type of string for all instances of the method in lib.d.ts .

Summary : Calling toString() on a variable of type any doesn't return a string. You can cast instead using <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. So toString() in this instance is not assumed to be the real version that returns a string. 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')];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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