问题描述
假设我有一个接受 2 个参数的函数,并且根据第一个参数的值,可能需要也可能不需要第二个参数.
Say I have a function that takes 2 args, and depending on the value of the first arg, the second arg may or may not be required.
例如:
function calculate(item: 'icon' | 'category', state: IState): void {
if (arg1 === 'icon') {
// code in which I don't need to access anything in state
}
if (arg1 === 'category') {
// code in which I do need to access state
}
}
如果我按原样运行它,如果我写,我会得到一个错误
If I were to run this as is, I would get an error if I write
calculate('icon') // will cause an error
这也会引发错误,因为我没有为第二个参数传递有效值
This will also throw an error because I am not passing a valid value for the second arg
calculate('icon', null) // will also cause an error
为了不出错,我必须这样称呼它
In order to not get any errors, I have to call it like this
calculate('icon', this.state) // acceptable as long as 'this.state' meets the IState definition
如果第一个参数 = 'icon',我希望能够在不传递第二个参数的情况下调用该函数.像这样
I want to be able to call the function without passing the second argument if the first argument = 'icon'. Like this
calculate('icon') // should not cause an error
但是,如果我这样调用计算它应该会导致错误
However, if I call calculate like this it should cause an error
calculate('category') // should cause an error
任何帮助将不胜感激!
推荐答案
您可以使用多个重载:
function calculate(item: 'icon'): void
function calculate(item: 'category', state: IState): void
function calculate(item: 'icon' | 'category', state?: IState): void {
if (item === 'icon') {
// code in which I don't need to access anything in state
}
if (item === 'category' && state) {
// code in which I do need to access state
}
}
calculate("icon")
calculate("category") //error
这篇关于TypeScript:如何根据第一个参数的值制作可选的第二个参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!