What it the best way in Typescript to only allow a number of value for a property ?
class Foo {
public type:string
class Foo {
public type: "foo1" | "foo2" | "foo3";
constructor() {}
}
or
type MyType = "foo1" | "foo2" | "foo3";
class Foo {
public type: MyType;
constructor() {}
}
But this is enforced only in compilation, and not in run time.
If you want to make sure that the value of Foo.type
is only one of those values then you need to check that at runtime:
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;
}
}
This is called String Literal Types.
You can use enums
:
enum MyType {
Foo1 = 'foo1',
Foo2 = 'foo2',
}
class FooClass {
private foo: MyType;
constructor(foo: MyType) {
this.foo = foo;
}
}
let bar = new FooClass(MyType.Foo2);
Typescript Docs
const TYPES = ['a', 'b', 'c'] as const; // TS3.4 syntax
type yourType = typeof TYPES[number]; // 'a'|'b'|'c';