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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…