win*_*rrr 5 javascript enums typescript ecmascript-6
TypeScript 枚举如下所示:
enum Direction {
Up = "Up",
Down = "Down",
Left = "Left",
Right = "Right"
}
Run Code Online (Sandbox Code Playgroud)
在我看来,像这样的枚举声明是不必要的工作。特别是考虑到 DRY 原则。是否有这样的声明的简写,以便当它们等于键时我不需要重复这些值?当然,我可以使用数字枚举,但它们有一个缺点,即在调试过程中不存在有意义的值。
例如 ES6 中的对象字面量简写:
firstname = 'firstname';
lastname = 'lastname';
fullname = {
firstname,
lastname
}
Run Code Online (Sandbox Code Playgroud)
但即使有了这个速记定义,我仍然需要写三遍firstname。难道就没有更简单的方法吗?
如果这样的事情能起作用那就太好了:
// for enums:
string_enum Direction {
Up,
Down,
Left,
Right
}
// for object literals:
fullname: {
'firstname',
'lastname'
}
Run Code Online (Sandbox Code Playgroud)
Dha*_*era -2
enum Directions {
"LEFT",
"RIGHT",
"UP",
"DOWN",
}
const goTo = (direction: Directions) => {
// use Directions[direction] to get the value.
// Otherwise you get only the index.
console.log("my direction is ", Directions[direction]);
// check directions
if (Directions[direction] === Directions[Directions.LEFT]) {
console.log("I go left...");
}
// when check directions not madary to extract that value.
if (direction === Directions.LEFT) {
console.log("I go left...");
}
};
goTo(Directions.LEFT);
Run Code Online (Sandbox Code Playgroud)