How to refer to Typescript enum in d.ts file, when using AMD?

前端 未结 3 1573
暖寄归人
暖寄归人 2020-12-28 17:03

I want to define a typescript interface to represent, say, an error. Something like this:

enum MessageLevel {
    Unknown,
    Fatal,
    Critical,
    Erro         


        
3条回答
  •  天涯浪人
    2020-12-28 17:43

    Almost two years later, this problem still exists. I could not find a good solution so I created a workaround, which tells your interface only that the type of the var is an enum, but not which enum. There's a "middleware" abstract wrapper for your main class which concretely sets the var type to be the needed enum.

    // globals.d.ts
    
    type EnumType = { [s: any]: any }
    
    interface IMyMessage {
      level: EnumType
    }
    
    // enums.ts
    
    export enum MessageLevel {
        Unknown,
        Fatal,
        Critical,
        Error,
        Warning,
        Info,
        Debug
    }
    
    // MyClass.ts
    
    import { MessageLevel } from 'enums'
    
    // If your MyMessage class is extending something, MyMessageWrapper has to 
    //  extend it instead!
    abstract class MyMessageWrapper extends X implements IMyMessage {
      abstract level: MessageLevel
    }
    
    class MyMessage extends MyMessageWrapper {
      level = MessageLevel.Unknown // works
      // level = MyOtherEnum.Unknown // doesn't work
    }
    

    Might be useful in some use cases.

提交回复
热议问题