Typescript - Allowed values for a property

前端 未结 3 463
北荒
北荒 2021-01-03 19:20

What it the best way in Typescript to only allow a number of value for a property ?

class Foo {
    public type:string         


        
相关标签:
3条回答
  • 2021-01-03 19:30
    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.

    0 讨论(0)
  • 2021-01-03 19:32

    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

    0 讨论(0)
  • 2021-01-03 19:53
    const TYPES = ['a', 'b', 'c'] as const; // TS3.4 syntax
    type yourType = typeof TYPES[number]; // 'a'|'b'|'c';
    
    0 讨论(0)
提交回复
热议问题