Is there a way to check for both `null` and `undefined`?
Since TypeScript is strongly-typed, simply using if () {}
to check for null
and undefined
doesn't sound right.
Does TypeScript have any dedicated function or syntax sugar for this?
Using a juggling-check, you can test both null
and undefined
in one hit:
if (x == null) {
If you use a strict-check, it will only be true for values set to null
and won't evaluate as true for undefined variables:
if (x === null) {
You can try this with various values using this example:
var a: number;
var b: number = null;
function check(x, name) {
if (x == null) {
console.log(name + ' == null');
}
if (x === null) {
console.log(name + ' === null');
}
if (typeof x === 'undefined') {
console.log(name + ' is undefined');
}
}
check(a, 'a');
check(b, 'b');
Output
"a == null"
"a is undefined"
"b == null"
"b === null"
if( value ) {
}
will evaluate to true
if value
is not:
null
undefined
NaN
- empty string
''
0
false
typescript includes javascript rules.