2

i am trying to build a class that build some dynamic methods on constructor stage, everything works well, but VS Code auto suggestion does not work for dynamic methods? how should we do that? here is the codeSandBox

i have also tried interface but still no luck

export default class A {
  private version = 1;
  get getVersion() {
    return this.version;
  }
  private actions = ["approve", "edit", "delete"];
  constructor() {
    this.actions.forEach(
      method =>
        (A.prototype[method] = route => {
          console.warn(method + " called");
        })
    );
  }
}

const B = new A();
console.warn(B.getVersion);
console.warn(B.approve()) // auto suggestion not available here  

1 Answer 1

1

You can do this... but it is really rather hacky. Meta programming like this is impossible to fully type check. Here's a playground with this solution.

First, tell TS that actions is a constant array so that it can narrow the type.

private actions = ["approve", "edit", "delete"] as const;

Next, create a mapped type that describes what your forEach method adds to the type.

type _A = {
    [K in A['actions'][number]]: (route: string) => void
}

Note that this has to be a type. It can't be an interface.

Finally, add an interface that extends this type alias. I expected TS to yell at me here about circularity, but apparently this is OK.

export default interface A extends _A {
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.