0

Any idea how to make dynamically visible class methods?

class Foo {
   method1() {}
   method2() {}
}

Sometimes i need to visible only method1, sometimes both.

One possible solution could be something like this, only problem is, that the method is then for the hinter visible as "property". It is just a small detail, but anyway i like if it is really method.

https://www.typescriptlang.org/play/?ssl=1&ssc=1&pln=10&pc=12#code/MYGwhgzhAEBiD29oG8BQ0PQgFzNglsNALZgDWApgDwDy0FAHthQHYAmM8ARgFYXDYAfAAp4AfgBc0GgEopCJADJpKdJnUAnCtgCuGltBYUA7nETCZ0SFZYBPANxqMAXyfQADhvjMBFNiW0AC3g2AEZhMCkcDXwWAHNLZGhXTGIgkIAmCxRXV1RgeBYcaAAzaABeM3gAOlJKYWQ07GCwqQByNucZVBLa9LCLIA

3
  • 3
    It is never a good idea to change visibility of a method dynamically ( even not possible in many languages), maybe you should create two classes , one with only method1 visible, the other with both. Commented Jan 7, 2020 at 16:42
  • Or add a little bit more context on what you are trying to do, so we can suggest something else. Commented Jan 7, 2020 at 16:43
  • 4
    Sounds like you just want to have interface segregation. Commented Jan 7, 2020 at 16:46

1 Answer 1

3

First: visibility is only checked during compile time, so bear in mind that there's no way to throw an error at runtime if you want to block access to a method. If this is your use-case, try something else.

If you want compile-time checking, what you're properly really after is better types.

So you have your class Foo:

class Foo {
   method1() {}
   method2() {}
}

If in parts of your code you don't want method1 to be called, it just means you'll need to define a type or interface that doesn't have that method.

type FooMethod2Only {
   method2: () => void;
}

method1 not being visible in some contexts really means you're working with a type that doesn't have that method.

So if you use a function as such:

function doSomething(foo: FooMethod2Only) {
  foo.method1();
}
doSomething(new Foo());

Then typescript will complain, because despite Foo having a method1, the argument type does not have it.

So instead of thinking about this in property/method visibility, think of it as using different types/interfaces for different purposes.

Sign up to request clarification or add additional context in comments.

2 Comments

not suitable for my case, i want to do this when creation. api = API.make().withMethods('POST') ... class API has all methods.
You might be able to solve that with generics, but how to handle that goes a bit beyond the scope of your original question. If you can, just open a new stackoverflow question that has a better example of this factory method.

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.