代码之家  ›  专栏  ›  技术社区  ›  Daniel R

导入枚举到接口断开接口

  •  2
  • Daniel R  · 技术社区  · 7 年前

    我要将枚举导入接口。(使用TypeScript2.5),但在另一个接口中使用该接口时会中断。下面是示例代码


    全枚举

    export enum ButtonType {
        Top = 1,
        Bottom = 2
    }
    
    other enums following ...
    

    按钮接口

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

    接口D.TS

    interface FormInterface { 
        buttos: ButtonInterface[]
    }
    

    结果是forminterface.d.ts中有一个错误

    找不到名称按钮接口


    有帮助的是像这样将按钮接口导入接口

    import { ButtonInterface } from "buttonInterface";
    

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

    2 回复  |  直到 7 年前
        1
  •  2
  •   Fenton    7 年前

    至于 TypeScript 2.9 您可以导入类型而不导入其包含的模块:

    import("./buttonInterface").ButtonInterface
    

    只要您使用的是TypeScript2.9或更高版本,就可以在您的场景中使用它。您还可以给它一个别名:

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

    您的ide/text编辑器可能无法完成此任务,但请通过运行 tsc 如果在编辑器中看到错误。

        2
  •  1
  •   Daniel R    7 年前

    我认为将枚举作为类型导入比较干净,因为人们不想编写包含接口的代码

    全枚举

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

    按钮接口

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

    接口D.TS

    interface FormInterface { 
        buttos: ButtonInterface[]
    }