I am facing a dilemma in my module where the public method of a public class is responsible for creating and returning a new instance of a private class. The stipulation is that only MyClass
should have the capability to instantiate MyClassPrivateHelper
.
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 {
/**/
}
}
In TypeScript, there is an error reported with this setup:
[ts] Return type of public method from exported class has or is using private name 'MyClassPrivateHelper'.
The objective is to export solely the "type" of the private class without allowing external code to directly instantiate it. For example,
const mycls = new module.MyClass();
// should be allowed
const helper: MyClassPrivateHelper = mycls.createHelper();
// should not be allowed
const helper = new module.MyClassPrivateHelper();
I attempted utilizing typeof
but did not find success.
export type Helper = typeof MyClassPrivateHelper
It seems like I may not fully grasp how "typeof" functions. My inquiries are:
- Why does exporting a type using
typeof
not function as expected? - How can I export a type without exposing the private class outside the module?