【问题标题】:How to declare an enum inside a class in typescript?如何在打字稿的类中声明枚举?
【发布时间】:2018-06-13 09:32:36
【问题描述】:

我可以在嵌套的namespace 中声明一个enum。但无法在class 中这样做。

namespace N {
  namespace NN {
    enum { ONE };  // OK
  }
}

namespace N {
  class C {
    public enum { ONE };  // Error: ';' expected
  }
}

正确的语法是什么?

【问题讨论】:

    标签: typescript syntax enums compiler-errors namespaces


    【解决方案1】:

    这个不直接支持,可以使用声明合并来达到类似的效果,可以将命名空间和类声明合并:

    class C {
    
    }
    namespace C {
        export enum OtherEnum { ONE };  // OK
    }
    
    C.OtherEnum.ONE // ok
    

    或者你可以使用自执行函数,但是语法更丑:

    class C {
        public static readonly MyEnum = (function() {  enum MyEnum { ONE } return MyEnum })();
    }
    C.MyEnum.ONE;
    

    【讨论】:

    • 第一种语法看起来不错。现在这意味着OtherEnum 不能是class C 的成员。有没有办法做到这一点?可能我们必须通过 dummy interface 然后实现到一个类中。
    • @iammilind 枚举的第一种方法总是静态的,第二种方法允许您将其设为实例枚举。虽然我不确定它的用例是什么。您确定您不仅需要枚举值作为成员吗? (enum OtherEnum { ONE }; class C { value: OtherEnum }
    猜你喜欢
    • 2014-05-29
    • 2021-11-10
    • 1970-01-01
    • 2020-04-30
    • 1970-01-01
    • 1970-01-01
    • 2020-01-29
    • 2018-06-12
    • 1970-01-01
    相关资源
    最近更新 更多