Implement methods class in separted files in typescript

Viewed 48

I try to define a class in a file and implements its method in separated files in order to use lazy loading.

For instance, here is the main class.

export default class Foo {

  private bar() {
    console.log("private bar");
  }

  public baz() {
    console.log("public baz");
  }
  
  public async qux(): Promise<void> {
    const { default: qux } = await import("./qux");
    return qux.call(this);
  }

}

and here is the content of "./qux.ts" :

export default function qux() {
  this.bar()
  this.baz();
}

This first error I got in this file is the following :

"'this' implicitly has type 'any' because it does not have a type annotation"

I also tried to set "noImplicitThis": false in my tsconfig. This remove my previous error but I can access to bar method which is private and I don't want this.


I tried an other implementation by removing the function binding and use typed parameter instead :

export default class Foo {

  private bar() {
    console.log("private bar");
  }

  public baz() {
    console.log("public baz");
  }
  
  public async qux(): Promise<void> {
    const { default: qux } = await import("./qux");
    return qux(this);
  }

}

and here is the content of "./qux.ts" :

import Foo from "./Foo";

export default function qux(this: Foo) {
  this.bar()
  this.baz();
}

And now the error is :

"Property 'bar' is private and only accessible within class 'Foo'"

I would like to benefit of classes modifiers (public - private - protected) and lazy loading. What pattern should I use ?

0 Answers
Related