在Typescript中,仅允许为属性设置特定值的最佳方法是什么?
class Foo {
public type:string;
// Possible values for type: ['foo1', 'foo2', 'foo3']
constructor() {}
}
我希望将这些类型设为唯一允许的类型,以防我在扩展Foo类时输入错误的类型。
在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;
}
}
这被称为字符串文字类型。
const TYPES = ['a', 'b', 'c'] as const; // TS3.4 syntax
type yourType = typeof TYPES[number]; // 'a'|'b'|'c';
enum MyType {
Foo1 = 'foo1',
Foo2 = 'foo2',
}
class FooClass {
private foo: MyType;
constructor(foo: MyType) {
this.foo = foo;
}
}
let bar = new FooClass(MyType.Foo2);
as const
是什么?为什么需要它? - Kartik Shahtypeof TYPES[number]
,它将被解析为一个字符串数组。const TYPES = ['a', 'b', 'c']; type yourType = typeof TYPES[number]; // string;
与const TYPES = ['a', 'b', 'c'] as const; type yourType = typeof TYPES[number]; // 'a'|'b'|'c';
更多信息可以在 TS 文档中找到 -> https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-4.html#const-assertions - Gynekolog