【问题标题】:Typescript - Allowed values for a property打字稿 - 属性的允许值
【发布时间】:2016-05-15 11:44:24
【问题描述】:

Typescript 中只允许一个属性有多个值的最佳方式是什么?

class Foo {
    public type:string;
    // Possible values for type: ['foo1', 'foo2', 'foo3']

    constructor() {}
}

我想让这些类型成为唯一允许的类型,防止我在扩展 Foo 类时输入错误的类型。

【问题讨论】:

    标签: typescript


    【解决方案1】:
    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;
        }
    }
    

    这叫String Literal Types

    【讨论】:

      【解决方案2】:

      你可以使用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

      【讨论】:

        【解决方案3】:
        const TYPES = ['a', 'b', 'c'] as const; // TS3.4 syntax
        type yourType = typeof TYPES[number]; // 'a'|'b'|'c';
        

        【讨论】:

        • 虽然这段代码可能会解决问题,但一个好的答案应该解释代码的什么以及它如何提供帮助。
        • as const 是做什么的?为什么需要它?
        • @KartikShah 没有 typeof TYPES[number] 将被解析为字符串数组。 const TYPES = ['a', 'b', 'c']; type yourType = typeof TYPES[number]; // string; vs const TYPES = ['a', 'b', 'c'] as const; type yourType = typeof TYPES[number]; // 'a'|'b'|'c'; 更多信息可以在 TS 文档中找到 -> typescriptlang.org/docs/handbook/release-notes/…
        • @Gynekolog 我明白了。感谢您的解释! :)
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-07-28
        • 2021-11-15
        • 2019-03-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多