打字稿块节点/模块工厂模式:错误TS4060

时间:2015-07-28 19:09:29

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

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

  

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

来自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时,正在导出类,从而无法在模块中确定范围。 e.g:

//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);

};

我错过了什么吗?在我看来,这个模式应该由打字稿支持,特别是在ES6编译中,模式变得更加突出。

1 个答案:

答案 0 :(得分:6)

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

如果您希望让编译器生成声明文件,您需要提供一个可用于返回类型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的返回值的类型。