Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript - Allowed values for a property

Tags:

typescript

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.

like image 515
biggbest Avatar asked May 15 '16 11:05

biggbest


People also ask

What is ?: In TypeScript?

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 .

How do you assign a value to an object in TypeScript?

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.

What is type guard in TypeScript?

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.


2 Answers

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.

like image 63
Nitzan Tomer Avatar answered Sep 19 '22 17:09

Nitzan Tomer


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

like image 23
SebaGnich Avatar answered Sep 18 '22 17:09

SebaGnich