快速解答
改变这个:
export let factory = () => {
return class Foo {}
};
到那个:
export let factory = () : any => {
return class Foo {}
};
更长的答案
此错误可能由 tsconfig.json 设置触发/强制:
{
"compilerOptions": {
...
"declaration": true // this should be false or omitted
但这不是原因,它只是一个触发器。真正的原因(在这里讨论Error when exporting function that returns class: Exported variable has or is using private name)来自 Typescript 编译器
当 TS 编译器发现这样的语句时
let factory = () => { ...
它必须开始猜测返回类型是什么,因为缺少该信息(检查 : <returnType> 占位符):
let factory = () : <returnType> => { ...
在我们的例子中,TS 会很快发现,返回的type 很容易猜到:
return class Foo {} // this is returned value,
// that could be treated as a return type of the factory method
所以,如果我们有类似的陈述(这与原始陈述完全不一样,但让我们试着用它作为一个例子来澄清会发生什么) 我们可以正确声明返回类型:
export class Foo {} // Foo is exported
export let factory = () : Foo => { // it could be return type of export function
return Foo
};
这种方法会奏效,因为 Foo 类 已导出,即对外可见。
回到我们的案例。 我们希望返回类型,该类型未导出。然后,我们必须帮助 TS 编译器决定返回类型是什么。
它可以是任何明确的:
export let factory = () : any => {
return class Foo {}
};
但更好的是有一些公共接口
export interface IFoo {}
然后使用返回类型这样的接口:
export let factory = () : IFoo => {
return class Foo implements IFoo {}
};