99

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.

Sam
  • 40,644
  • 36
  • 176
  • 219
  • 1
    Depends on what you want to check, someone could have called your method `foo(1, undefined)`. You could check `arguments.length`. – Evan Trimboli Jan 05 '14 at 23:32
  • @EvanTrimboli, thanks; I think you're right. I've updated the question to clarify that either possibility is acceptable. – Sam Jan 05 '14 at 23:42
  • I'm voting to close this question as unclear since it has run its course and ended up having multiple "correct" answers depending on how it's interpreted. – Sam Apr 25 '19 at 02:17
  • I don't understand why no one suggests using `??` – A_P Dec 14 '22 at 21:36

5 Answers5

49

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();
}
Community
  • 1
  • 1
Tod Birdsall
  • 17,877
  • 4
  • 38
  • 40
  • 6
    I wonder about this. https://github.com/Microsoft/TypeScript/wiki/Coding-guidelines#null-and-undefined says "don't use null". https://basarat.gitbooks.io/typescript/content/docs/tips/null.html says "Null is bad". I'd be interested to find out more about the potential pitfalls of using `null` instead of `undefined`. – Sam Finnigan Nov 01 '16 at 11:32
  • 2
    It says "NOTE: These are Coding Guidelines for TypeScript Contributors." – throws_exceptions_at_you Feb 14 '17 at 13:24
  • 1
    If you want to check if it has been set is it safe to check `if (b != null) doSomethingWith(b);`? – TheJKFever Aug 04 '17 at 21:45
  • 3
    `null` and `undefined` are different values. In this example `DoSomething('smth', null)` we DO provide optional argument and `doSomething()` will be executed. If optional argument is not passed, then it will be `undefined`. – Vladimir Prudnikov Jan 06 '18 at 17:51
  • @TheJKFever yes `if (b != null) ...` does work as well. – reads0520 Aug 07 '18 at 19:38
  • Note: this works because (undefined == null) is true – Ray Hulha Feb 03 '19 at 02:22
22

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
Sebastian
  • 1,321
  • 9
  • 21
Evan Trimboli
  • 29,900
  • 6
  • 45
  • 66
  • Yes, that generally seems to work in the same way that my example solution does. However, since this is a general question, I think it's safer to use the `typeof` check instead. – Sam Jan 06 '14 at 03:00
  • 1
    I don't really understand what you mean by "general" question. Typically the only time you want to use `typeof` is if the variable isn't defined. eg `typeof somevar === 'undefined'`. – Evan Trimboli Jan 06 '14 at 03:07
  • By "general question", I mean this question is not really providing any context, so I think it's best that the answer is also appropriate for all contexts. – Sam Jan 06 '14 at 03:18
  • 3
    The reason I believe the `typeof` check is safer is `undefined` can be redefined (either intentionally or accidentally) in some browsers. – Sam Jan 06 '14 at 03:20
  • Unfortunately, my original question has been interpreted a couple of different ways. My intent was really about leaving an optional parameter absent, as in `fn(1)` in this answer. In both TypeScript and JavaScript, the value is `undefined`, so Evan's answer here is closest to the mark and also shows that he read the intent behind the question. So I'm marking this answer as accepted. – Sam Apr 25 '19 at 02:06
  • I recently updated EvanTrimboli 's answer, and removed the first parameter, so for anyone reading Sam's last comment: `fn(1)` points to the first function call, now `fn()`. – Sebastian Jul 17 '20 at 11:11
11

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);
        }
    }
}
Vladimir Prudnikov
  • 6,974
  • 4
  • 48
  • 57
  • 9
    The `isUndefined` util function has been deprecated since v4. Use `value === undefined` instead. – Aaron Greenlee Feb 02 '19 at 12:19
  • 1
    You are right. The reason they (util.is* functions) were deprecated is because there were some issues, and fixing them will result in a lot of broken code. They decided to deprecate. I just created my own utils module and defined these functions. – Vladimir Prudnikov Feb 03 '19 at 17:27
  • As a side note: isUndefined is deprecated since v4.0.0 according to index.d.ts – Bas van Dijk Feb 20 '19 at 13:12
8

you could simple add an optional parameter with an default value like this

function DoSomething(a, b: boolean=null) {
    if(b == null)
    {
      //parameter was not set
    }
    else
    {
    //parameter is true or false...no other option available
    }
}
Tobias Koller
  • 2,116
  • 4
  • 26
  • 46
1

From here works without problems:

function getSchool(name: string, address?: string, pinCode?: string): string {
    if (typeof address === 'undefined') {
        console.log('address not defined');
    }
    if (typeof pinCode === 'undefined') {
        console.log('pincode not defined');
    }
    //...
}
Stephen M Irving
  • 1,324
  • 9
  • 20
Pavel_K
  • 10,748
  • 13
  • 73
  • 186