What it the best way in Typescript to only allow a number of value for a property ?
class Foo { public type:string; // Possible values for type: ['foo1', 'foo2', 'foo3'] constructor() {} }
I'd like to make those types the only allowed types, preventing me to put a wrong type when extending Foo class.
What does ?: mean in TypeScript? Using a question mark followed by a colon ( ?: ) means a property is optional. That said, a property can either have a value based on the type defined or its value can be undefined .
To use the Object. assign() method in TypeScript, pass a target object as the first parameter to the method and one or more source objects, e.g. const result = Object. assign({}, obj1, obj2) . The method will copy the properties from the source objects to the target object.
A type guard is a TypeScript technique used to get information about the type of a variable, usually within a conditional block. Type guards are regular functions that return a boolean, taking a type and telling TypeScript if it can be narrowed down to something more specific.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With