Typescript - 属性的允许值
问题描述:
Typescript中最好的方法是只允许一些属性值?Typescript - 属性的允许值
class Foo {
public type:string;
// Possible values for type: ['foo1', 'foo2', 'foo3']
constructor() {}
}
我想使这些类型成为唯一允许的类型,防止我在扩展Foo类时放错类型。
答
class Foo {
public type: "foo1" | "foo2" | "foo3";
constructor() {}
}
或
type MyType = "foo1" | "foo2" | "foo3";
class Foo {
public type: MyType;
constructor() {}
}
但这是强制执行只能在编译,而不是在运行时。
如果你想确保的Foo.type
值仅仅是对那些值中的一个,那么你需要检查在运行时:
type MyType = "foo1" | "foo2" | "foo3";
class Foo {
public type: MyType;
constructor() {}
setType(type: MyType): void {
if (["foo1", "foo2", "foo3"].indexOf(type) < 0) {
throw new Error(`${ type } is not allowed`);
}
this.type = type;
}
}
这就是所谓的String Literal Types。