【发布时间】:2018-08-29 18:01:34
【问题描述】:
我有一个模块,其中公共类的公共方法创建并返回私有类的新实例。要求是MyClassPrivateHelper 只能由MyClass 实例化。
class MyClassPrivateHelper {
constructor(private cls: MyClass) {
}
public someHelperMethod(arg): void {
this.cls.someMethod();
}
}
export class MyClass {
public createHelper(): MyClassPrivateHelper { // error here
return new MyClassPrivateHelper(this);
}
public someMethod(): void {
/**/
}
}
这样安排 TypeScript 会报错:
[ts] Return type of public method from exported class has or is using private name 'MyClassPrivateHelper'.
我的目标是只导出私有类的“类型”,而不让使用模块的代码直接实例化它。例如
const mycls = new module.MyClass();
// should be allowed
const helper: MyClassPrivateHelper = mycls.createHelper();
// should not be allowed
const helper = new module.MyClassPrivateHelper();
我曾尝试像这样使用typeof,但没有成功。
export type Helper = typeof MyClassPrivateHelper
也许我不明白“typeof”是如何工作的。我的问题是:
- 为什么使用
typeof导出类型不起作用? - 如何在不暴露模块外部私有类的情况下导出类型?
【问题讨论】:
-
MyClassPrivateHelper 类型到底是什么? MyClassPrivateHelper 在上面的代码中没有公共成员。
-
为
MyClassPrivateHelper创建一个接口。导出并改用它。 -
我无法复制您示例中的错误。你使用的是最新版本的 TypeScript 吗?
-
@Behrooz 如果你启用
declarationemitting 就会发生这种情况 -
@estus 我更新了代码以添加一个公共方法来显示使用情况。 @Behrooz 我正在使用 TS 版本 2.7.2。正如提香所说,我的
tsconfig中有"declaration": true。
标签: typescript typescript-typings