在Typescript中最好的方法是只允许属性的多个值?
class Foo {
public type:string;
// Possible values for type: ['foo1', 'foo2', 'foo3']
constructor() {}
}
Run Code Online (Sandbox Code Playgroud)
我想让这些类型成为唯一允许的类型,防止我在扩展Foo类时输入错误的类型.
Nit*_*mer 41
class Foo {
public type: "foo1" | "foo2" | "foo3";
constructor() {}
}
Run Code Online (Sandbox Code Playgroud)
要么
type MyType = "foo1" | "foo2" | "foo3";
class Foo {
public type: MyType;
constructor() {}
}
Run Code Online (Sandbox Code Playgroud)
但这仅在编译时强制执行,而不是在运行时执行.
如果要确保值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;
}
}
Run Code Online (Sandbox Code Playgroud)
这称为字符串文字类型.
const TYPES = ['a', 'b', 'c'] as const; // TS3.4 syntax
type yourType = typeof TYPES[number]; // 'a'|'b'|'c';
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7281 次 |
| 最近记录: |