【发布时间】:2019-08-05 23:48:51
【问题描述】:
假设我有一个需要 2 个参数的函数,根据第一个参数的值,可能需要也可能不需要第二个参数。
例如:
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
}
}
如果我按原样运行,我会得到一个错误,如果我写
calculate('icon') // will cause an error
这也会引发错误,因为我没有为第二个参数传递有效值
calculate('icon', null) // will also cause an error
为了不出错,我必须这样称呼它
calculate('icon', this.state) // acceptable as long as 'this.state' meets the IState definition
如果第一个参数 = 'icon',我希望能够在不传递第二个参数的情况下调用该函数。像这样
calculate('icon') // should not cause an error
但是,如果我这样调用计算应该会导致错误
calculate('category') // should cause an error
任何帮助将不胜感激!
【问题讨论】:
标签: typescript typescript-typings