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

前端 未结 3 1581
暖寄归人
暖寄归人 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:45

    The best solution may depend on whether you have a preference for the actual JavaScript variable being a number, a string, or otherwise. If you don't mind String, you can do it like this:

    ///messagelevel.d.ts
    export type MessageLevel = "Unknown" | "Fatal" | "Critical" | "Error";
    
    
    
    ///main.d.ts
    import * as ml from "./MessageLevel";
    
    interface IMyMessage {
        name: string;
        level: ml.MessageLevel;
        message: string;
    }
    

    So in the end JavaScript, it will simply be represented as a string, but TypeScript will flag an error anytime you compare it to a value not in that list, or try to assign it to a different string. Since this is the closest that JavaScript itself has to any kind of enum (eg, document.createElement("video") rather than document.createElement(ElementTypes.VIDEO), it might be one of the better ways of expressing this logic.

提交回复
热议问题