Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
121
rated 0 times [  123] [ 2]  / answers: 1 / hits: 44584  / 7 Years ago, mon, july 3, 2017, 12:00:00

I wanted to use string enums in typescript but I can't see a support for reversed mapping in it.
I have an enum like this:



enum Mode {
Silent = Silent,
Normal = Normal,
Deleted = Deleted
}


and I need to use it like this:



let modeStr: string;
let mode: Mode = Mode[modeStr];


and yes I don't know what is it there in modeStr string and I need it parsed to the enum or a fail at parsing in runtime if the string is not presented in the enum definition.
How can I do that as neat as it can be?
thanks in advance


More From » node.js

 Answers
7

We can make the Mode to be a type and a value at the same type.



type Mode = string;
let Mode = {
Silent: Silent,
Normal: Normal,
Deleted: Deleted
}

let modeStr: string = Silent;
let mode: Mode;

mode = Mode[modeStr]; // Silent
mode = Mode.Normal; // Normal
mode = Deleted; // Deleted
mode = Mode[unknown]; // undefined
mode = invalid; // invalid


A more strict version:



type Mode = Silent | Normal | Deleted;
const Mode = {
get Silent(): Mode { return Silent; },
get Normal(): Mode { return Normal; },
get Deleted(): Mode { return Deleted; }
}

let modeStr: string = Silent;
let mode: Mode;

mode = Mode[modeStr]; // Silent
mode = Mode.Normal; // Normal
mode = Deleted; // Deleted
mode = Mode[unknown]; // undefined
//mode = invalid; // Error


String Enum as this answer:



enum Mode {
Silent = <any>Silent,
Normal = <any>Normal,
Deleted = <any>Deleted
}

let modeStr: string = Silent;
let mode: Mode;

mode = Mode[modeStr]; // Silent
mode = Mode.Normal; // Normal
//mode = Deleted; // Error
mode = Mode[unknown]; // undefined

[#57229] Friday, June 30, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
victorr

Total Points: 193
Total Questions: 86
Total Answers: 105

Location: Pitcairn Islands
Member since Thu, Jun 24, 2021
3 Years ago
victorr questions
Fri, Nov 13, 20, 00:00, 4 Years ago
Sat, Jul 25, 20, 00:00, 4 Years ago
Thu, Jun 11, 20, 00:00, 4 Years ago
;