【问题标题】:Import Enum to Interface breakes Interface将枚举导入接口中断接口
【发布时间】:2018-11-14 14:45:10
【问题描述】:

我想将枚举导入接口。 (使用打字稿2.5)但这会在另一个界面中使用该界面。这是示例代码


allEnums.ts

export enum ButtonType {
    Top = 1,
    Bottom = 2
}

other enums following ...

buttonInterface.d.ts

import { ButtonType } from "allEnums";
interface ButtonInterface {
    buttonType: ButtonType
}

formInterface.d.ts

interface FormInterface { 
    buttos: ButtonInterface[]
}

结果是 formInterface.d.ts 中的错误

找不到名称按钮接口


像这样将 ButtonInterface 导入到 FormInterface 会有帮助

import { ButtonInterface } from "buttonInterface";

但我认为导入接口并不是一个好的解决方案

【问题讨论】:

    标签: typescript enums interface


    【解决方案1】:

    我认为将枚举作为类型导入更简洁,因为不想编写包含接口的代码

    allEnums.ts

    export enum ButtonType {
        Top = 1,
        Bottom = 2
    }
    

    buttonInterface.d.ts

    type ButtonType = import('allEnums').ButtonType;
    interface ButtonInterface {
        buttonType: ButtonType
    }
    

    formInterface.d.ts

    interface FormInterface { 
        buttos: ButtonInterface[]
    }
    

    【讨论】:

      【解决方案2】:

      TypeScript 2.9 开始,您可以在不导入包含模块的情况下导入类型:

      import("./buttonInterface").ButtonInterface
      

      只要您使用 TypeScript 2.9 或更高版本,您就可以在您的场景中使用它。你也可以给它一个别名:

      type ButtonInterface = import('./buttonInterface').ButtonInterface;
      
      interface FormInterface { 
          buttos: ButtonInterface[]
      }
      

      您的 IDE/文本编辑器可能无法满足此要求,但如果您看到编辑器内错误,请运行 tsc 检查。

      【讨论】:

      • 谢谢,这行得通!但这仍然需要导入接口。我认为这不是一个好的风格。但是将枚举声明为类型也可以。我将发布此代码
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-07-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多