如何从 TypeScript 函数返回一个类?

新手上路,请多包涵

我将 TypeScript 与依赖注入库一起使用,它的工作方式与 Angular 1 非常相似——基本上: _注册一个工厂,将你的依赖项作为参数_。

这就是我在 ES6 中注册课程的方式

export let factory = () => {
    return class Foo {}
};

如果我用 TypeScript 写同样的东西:

 export let factory = () => {
    return class Foo {}
};

它无法编译并出现错误

错误 TS4025:导出的变量“工厂”具有或正在使用私有名称“Foo”。

有没有办法让 TypeScript 从工厂函数返回一个类?

原文由 MrSimonEmms 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 440
1 个回答

快速回答

改变这个:

 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 {}
};

原文由 Radim Köhler 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题