在TypeScript中导出类和类型的最佳方法

时间:2020-04-26 12:57:48

标签: javascript typescript

遵循此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;
    }
}

如果我将此文档应用于项目,则我的短毛猫会用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 {
...
}

1 个答案:

答案 0 :(得分:2)

您可以单独导出类和接口,而无需命名空间:

export interface MyClassMethodOptions {
        width?: number;
        height?: number;
}

export default class MyClass {

    constructor(someParam?: string);

    someProperty: string[];

    myMethod(opts: MyClassMethodOptions): number;

}