当使用 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 时,该类将被导出,从而违背了在模块中限定其作用域的目的。例如:
//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
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)