以下代码可用于enum在TypeScript中创建:
enum e {
hello = 1,
world = 2
};
Run Code Online (Sandbox Code Playgroud)
并且可以通过以下方式访问这些值:
e.hello;
e.world;
Run Code Online (Sandbox Code Playgroud)
如何创建enum带字符串值?
enum e {
hello = "hello", // error: cannot convert string to e
world = "world" // error
};
Run Code Online (Sandbox Code Playgroud) 我正在为TypeScript的Google maps API制作定义文件.
我需要定义类似枚举的例如.google.maps.Animation它包含两个属性:BOUNCE和DROP.
应该如何在TypeScript中完成?
我知道JavaScript(以及TypeScript)在很多情况下都支持省略分号.不过我想在TypeScript Deep Dive中建议添加分号是明确的
但是,我找不到列出使用分号的指南.例如,请查看以下代码
class Person {
private name: string; // A
constructor(name: string) {
this.name = name;
}; // B
public add = () => {
return "C";
}; // C
}; // D
Run Code Online (Sandbox Code Playgroud)
我很确定在A处使用分号.但是B,C,D以及我的例子未涵盖的所有其他案例呢?
编辑:我应该补充一点,我不是在问省略分号的位置,而是在哪里添加分号.像往常一样的答案不能满足我的需求,因为我无法添加;后public.我想知道究竟在哪里放分号.
有没有办法让TypeScript枚举与JSON中的字符串兼容?
例如:
enum Type { NEW, OLD }
interface Thing { type: Type }
let thing:Thing = JSON.parse('{"type": "NEW"}');
alert(thing.type == Type.NEW); // false
Run Code Online (Sandbox Code Playgroud)
我想 thing.type == Type.NEW是真的.或者更具体地说,我希望我可以指定enum要定义为字符串的值,而不是数字.
我知道我可以使用,thing.type.toString() == Type[Type.NEW]但这很麻烦,似乎使枚举类型注释混乱和误导,这违背了它的目的.从技术上讲,JSON 不提供有效的枚举值,因此我不应该将属性键入枚举.
所以我现在正在做的是使用带有静态常量的字符串类型:
const Type = { NEW: "NEW", OLD: "OLD" }
interface Thing { type: string }
let thing:Thing = JSON.parse('{"type": "NEW"}');
alert(thing.type == Type.NEW); // true
Run Code Online (Sandbox Code Playgroud)
这让我得到了我想要的用法,但是类型注释string太宽泛且容易出错.
我有点惊讶JavaScript的超集没有基于字符串的枚举.我错过了什么吗?有没有不同的方法可以做到这一点?
更新TS 1.8
使用字符串文字类型是另一种选择(感谢@basaret),但要获得所需的类似枚举的用法(上图),它需要定义两次值:一次是字符串文字类型,一次是值(常量或命名空间):
type Type …Run Code Online (Sandbox Code Playgroud)