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.
Edit
Unfortunately, this question wasn't as clear as it should have been, particularly if it's skim-read. It was meant to be about how to cleanly check if an optional parameter is completely omitted, as in:
DoSomething("some value");
I've accepted Evan's answer since his solution (b === undefined
) is cleaner than the one in my question (typeof b === 'undefined'
) while still having the same behaviour.
The other answers are definitely useful, and which answer is correct for you depends on your use case.