【问题标题】:Best way to export both class and types in TypeScript在 TypeScript 中导出类和类型的最佳方法
【发布时间】:2020-08-09 23:08:12
【问题描述】:

遵循stackoverflow question(~2016)和打字稿about Class modules官方文档

声明类模块声明文件应使用namespace,方式如下:

export = MyClass;

declare class MyClass {
    constructor(someParam?: string);

    someProperty: string[];

    myMethod(opts: MyClass.MyClassMethodOptions): number;
}

declare namespace MyClass {
    export interface MyClassMethodOptions {
        width?: number;
        height?: number;
    }
}

如果我将此文档应用到我的项目中,我的 linter 会使用 no-namespace 规则 (doc about this rule) 向我尖叫:

ES2015 模块语法优于自定义 TypeScript 模块和命名空间。eslint@typescript-eslint/no-namespace 窥视问题(⌥F8)

还有

MyClass 已定义

这仍然是处理 Class 模块中类型的首选方式吗?

编辑 重要的是,该类默认保持导出

解决方案

import myClass from 'myclass.ts'

export default myClass

export interface myObject {
...
}

【问题讨论】:

    标签: javascript typescript


    【解决方案1】:

    您可以自己导出类和接口,无需命名空间:

    export interface MyClassMethodOptions {
      width?: number;
      height?: number;
    }
    
    export default class MyClass {
      constructor(someParam?: string);
    
      someProperty: string[];
    
      myMethod(opts: MyClassMethodOptions): number;
    }
    

    【讨论】:

    • 嘿。此解决方案的问题是默认情况下不导出 MyClass。我的模块就是这种情况。所以我会有这个错误:`× TypeError: myClass is not a constructor
    • 我更新了评论中的代码以将类导出为默认值
    • 好吧,现在这不是一个类型而是实际的类号?
    • 您要导出哪些类型?
    • 我的错,这确实有效。我从我的 class.ts 中导入了该类并将其导出到该文件中,并且它起作用了。谢谢!
    猜你喜欢
    • 2020-11-05
    • 2021-10-23
    • 2012-07-04
    • 2016-04-30
    • 1970-01-01
    • 2011-04-14
    • 1970-01-01
    • 2020-09-03
    • 1970-01-01
    相关资源
    最近更新 更多