Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check whether an optional parameter was provided?

Tags:

typescript

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.

like image 750
Sam Avatar asked Jan 05 '14 23:01

Sam


People also ask

How do I know if optional parameter exists in darts?

The Dart-Homepage shows following: It turns out that Dart does indeed have a way to ask if an optional parameter was provided when the method was called. Just use the question mark parameter syntax.

How do you check if a parameter is provided in Python?

Just do 'a' in explicit_params to check if parameter a is given explicitly.

How do you specify an optional parameter?

Optional parameters are defined at the end of the parameter list, after any required parameters. If the caller provides an argument for any one of a succession of optional parameters, it must provide arguments for all preceding optional parameters. Comma-separated gaps in the argument list aren't supported.


2 Answers

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(); } 
like image 72
Tod Birdsall Avatar answered Sep 18 '22 18:09

Tod Birdsall


You can just check the value to see if it's undefined:

var fn = function(a) {     console.log(a === undefined); };      fn();          // true fn(undefined); // true fn(null);      // false fn('foo');     // false 
like image 34
Evan Trimboli Avatar answered Sep 18 '22 18:09

Evan Trimboli