打字稿阻止节点/模块出厂模式:错误TS4060 [英] Typescript blocks node/module factory pattern: error TS4060

查看:44
本文介绍了打字稿阻止节点/模块出厂模式:错误TS4060的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

When using ES6 module syntax to export a factory function which returns an instance of a class Typescript produce the following error:

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

error TS4060: Return type of exported function has or is using private name '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时,将导出类,从而无法在模块中进行范围限定.例如:

This legitimate ES6 javascript. However, the only work around i've found is to export the class. Which means when it is compiled to ES6 the Class is being exported defeating the purpose of scoping it in the module. 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编译中,该模式变得更加突出.

Am I missing something? It seems to me that this pattern should be supported by typescript, especially in ES6 compilation where the pattern becomes more prominent.

推荐答案

仅当您尝试自动生成声明文件时,这是一个错误,因为TypeScript不会向该文件中发出任何内容来再现该文件的形状.您的模块具有100%的精度.

This is only an error if you're trying to automatically produce a declaration file, because there's nothing that TypeScript could emit into that file that would reproduce the shape of your module with 100% precision.

如果要让编译器生成声明文件,则需要提供可用于 getPaths 的返回类型的类型.您可以使用内联类型:

If you want to have the compiler produce the declaration file, you'll need to provide a type that you can use for the return type of getPaths. You could use an inline type:

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 的返回值的类型.

The second is probably preferred because this gives people who import your module some name to use to refer to the type of the return value of getPaths.

这篇关于打字稿阻止节点/模块出厂模式:错误TS4060的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆