当使用ES6模块语法导出一个返回类实例的工厂函数时,Typescript会产生以下错误:
从paths.ts:错误TS4060:导出函数的返回类型已经或正在使用私有名'Paths'.
//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无法在该文件中以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
返回值的类型。