[英]How to choose method to call depending on argument
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
.我有一个方法
foo(msg: string, arg: string)
它将从bar
调用一个方法,它是一个 object 在与foo
相同的 class 中。 Which method depends on the value of arg
.哪种方法取决于
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
.换句话说,我想从
bar
调用方法arg
。 And this works as it should.这可以正常工作。 However, I would like to restrict the values that
arg
can have.但是,我想限制
arg
可以具有的值。 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".参数
arg
永远不会被“构造”。 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!"我在这里担心的是 1)安全和人们说“NOOOOO。那是不好的做法!” and 2) that my IDE cannot detect spelling errors with my approach.
和 2) 我的 IDE 无法用我的方法检测拼写错误。
So my goal here is a convenient method to call a method from bar
depending on the argument arg
.所以我的目标是根据参数
arg
从bar
调用方法的便捷方法。 Preferably something that makes an IDE capable of detecting spelling errors.最好是使 IDE 能够检测拼写错误的东西。 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 https://www.typescriptlang.org/docs/handbook/literal-types.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.