0

I have a class that have some static methods in it, and I want to keep the same name between a public method and a private one, how can I overload it?

export class MyClass {

    public static methodX(arg: ArgTypeA): void {
        // method implementation, it will call the private method methodX(arg: ArgTypeB)
    }

    private static methodX(arg: ArgTypeB): void {
        // method implementation
    }

}
  • I provided an answer, but I suspect this is an [XY Problem](https://xyproblem.info/). There's probably a better way to structure what you are trying to accomplish here. – Alex Wayne Mar 13 '23 at 19:33
  • It's probably true, I'll try to think in a better structure, but thanks anyway for the help! – Rafael Furtado Mar 14 '23 at 10:35

1 Answers1

2

You may only one value for each property key on anything. This is true for plain objects, and it's true for class instance methods and it's true for static class methods.

So you my not have two methods with the exact same name where one is private and one is public. They must have different names.

Such as:

export class MyClass {

    public static methodX(arg: ArgTypeA): void {
        // method implementation, it will call the private method methodX(arg: ArgTypeB)
    }

    private static methodXCoreImplementation(arg: ArgTypeB): void {
        // method implementation
    }

}

One way to achieve something close to this would be to use private fields. That uses the # prefix to declare a private field which is completely inaccessible to the outside.

And foo is technically a different property name to #foo, so this should work:

export class MyClass {
    public static methodX(arg: string): void {
        this.#methodX(arg)
    }

    static #methodX(arg: string): void {
        console.log('hello from private field method:', arg)
    }
}

MyClass.methodX('test') // "hello from private field method:",  "test"

See Playground

Alex Wayne
  • 178,991
  • 47
  • 309
  • 337