【问题标题】:Typescript blocks node/module factory pattern: error TS4060打字稿块节点/模块工厂模式:错误 TS4060
【发布时间】:2015-07-28 19:09:29
【问题描述】:

当使用 ES6 模块语法导出返回类 Typescript 实例的工厂函数时,会产生以下错误:

错误 TS4060:导出函数的返回类型已经或正在使用私有名称“路径”。

来自paths.ts:

//Class scoped behind the export
class Paths {

    rootDir: string;

    constructor(rootDir: string) {

        this.rootDir = rootDir;

    };


};

//Factory function: returns instances of Paths
export default function getPaths(rootDir:string){ 

    return new Paths(rootDir);

};

这个合法的 ES6 javascript。但是,我发现的唯一解决方法是导出类。这意味着当它被编译为 ES6 时,该类被导出,从而违背了在模块中确定它的目的。例如:

//Class now exported
export class Paths {

    rootDir: string;

    constructor(rootDir: string) {

        this.rootDir = rootDir;

    };


};

//Factory function: returns instances of Paths
export default function getPaths(rootDir:string){ 

    return new Paths(rootDir);

};

我错过了什么吗?在我看来,typescript 应该支持这种模式,尤其是在模式变得更加突出的 ES6 编译中。

【问题讨论】:

    标签: typescript ecmascript-6 es6-module-loader


    【解决方案1】:

    如果您尝试自动生成声明文件,这只是一个错误,因为 TypeScript 不会向该文件中发出任何可以 100% 精确再现模块形状的内容。

    如果您想让编译器生成声明文件,您需要提供一个可用于返回类型getPaths 的类型。您可以使用内联类型:

    export default function getPaths(rootDir:string): { rootDir: string; } { 
      return new Paths(rootDir);
    };
    

    或者定义一个接口:

    class Paths implements PathShape {
        rootDir: string;
        constructor(rootDir: string) {
            this.rootDir = rootDir;
        }
    }
    export interface PathShape {
        rootDir:string;
    }
    export default function getPaths(rootDir:string): PathShape { 
      return new Paths(rootDir);
    }
    

    第二个可能是首选,因为这给import你的模块的人提供了一些名称来引用getPaths的返回值的类型。

    【讨论】:

    • 非常感谢你的真棒!已将 --declaration 标志设置为 true。
    猜你喜欢
    • 1970-01-01
    • 2022-01-14
    • 1970-01-01
    • 2018-04-20
    • 2020-01-03
    • 2019-01-16
    • 2021-10-16
    • 2017-03-11
    • 1970-01-01
    相关资源
    最近更新 更多