I have a method foo(msg: string, arg: string) which will call a method from bar, which is an object in the same class as foo. Which method depends on the value of arg. My problem is how I should do that in a good way.
In my real code base, I want to use it for refactoring. Because it looks like this:
add() { foo('Adding', 'add'); }
sub() { foo('Subtracting', 'sub'); }
mul() { foo('Multiplying', 'mul'); }
div() { foo('Dividing', 'div'); }
I have a method like this:
foo(msg: string, arg: string) {
console.log(msg);
this.bar[arg]();
// More code
}
In other words, I want to call the method arg from bar. And this works as it should. However, I would like to restrict the values that arg can have. I suppose I could do something like:
foo(arg: string) {
if(arg !== 'fun1' && arg !== 'fun2') {
// Handle error
}
this.bar[arg]();
}
The argument arg will never be "constructed". I use constant values directly all the time, like
foo('fun1');
and never something like
// Example of how I will NOT use this
let arg = someFunctionReturningAString();
foo(arg);
My concerns here are 1) safety and people saying "NOOOOO! That's bad practice!" and 2) that my IDE cannot detect spelling errors with my approach.
So my goal here is a convenient method to call a method from bar depending on the argument arg. Preferably something that makes an IDE capable of detecting spelling errors. How do I do that?
You could use literal types in your signature, like:
foo(msg: string, arg: 'add' | 'sub' | 'mul' | 'div') {
console.log(msg);
this.bar[arg]();
// More code
}
https://www.typescriptlang.org/docs/handbook/literal-types.html