How can I check whether an optional parameter was provided?
Given a function with optional parameters:
function DoSomething(a, b?) {
/** Implementation */
}
How can I determine whether an optional parameter was provided from within the function body? Currently, the best way to do this that I can think of is:
typeof b === 'undefined'
But this is kind of messy and not straight-forward to read. Since TypeScript provides optional parameter support, I'm hoping it also has an intuitive way to check if a parameter was provided.
As the above example shows, I don't mind whether the optional parameter was explicitly set to undefined
or not supplied at all.
After googling "typescript check for undefined", I saw this question at the top of the results, but the answer given by Evan Trimboli did not solve my problem.
Here is the answer that ultimately solved my problem. The following code is what I settled on. It should work in cases where the value equals null
or undefined
:
function DoSomething(a, b?) {
if (b == null) doSomething();
}
TypeScript's util
module has function isUndefined()
. You can use it like this.
import {isUndefined} from "util";
class A {
test(b?: string): string {
if (isUndefined(b)) {
return "UNDEFINED";
} else {
return ("DEFINED" + b);
}
}
}
你可以简单地添加一个可选参数,并使用默认值
function DoSomething(a, b: boolean=null) {
if(b == null)
{
//parameter was not set
}
else
{
//parameter is true or false...no other option available
}
}
链接地址: http://www.djcxy.com/p/76358.html
上一篇: 如何在JavaScript中将传递给函数的变量设置为null
下一篇: 我如何检查是否提供了可选参数?