As we saw in Data types tutorial, TypeScript has two special types, null and undefined. These two types can have the values 'null' and 'undefined' respectively.
These two special types can be part of a union type. They can also be used in very simple type guards.
Example
function show(x: number | null | undefined) {
if(x === undefined){
console.log("value not set");
}else if(x === null){
console.log("value is null");
}else{
console.log(x);
}
}
let x = 10;
let y;
let z = null;
show(x);
show(y);
show(z);
Output10 value not set value is null
Or we can just use number | null which will accept undefined values as well:
function show(x: number | null) {
if(x === undefined){
console.log("value not set");
}else if(x === null){
console.log("value is null");
}else{
console.log(x);
}
}
let x = 10;
let y;
let z = null;
show(x);
show(y);
show(z);
Output10 value not set value is null
Or if we just user number in above example, nothing prevents passing null/undefined.
function show(x: number) {
if (x === undefined) {
console.log("value not set");
} else if (x === null) {
console.log("value is null");
} else {
console.log(x);
}
}
let x = 10;
let y;
let z = null;
show(x);
show(y);
show(z);
Output10 value not set value is null
But if we compile above last example with --strictNullChecks flag:
16:6 - error TS2345: Argument of type 'null' is not assignable to parameter of type 'number'.
16 show(z);
^
Use of optional operator ?
Using ? is equivalent to the above unless we use --strictNullChecks flag.
Without --strictNullChecks:
function show(x?: number) {
if (x === undefined) {
console.log("value not set");
} else if (x === null) {
console.log("value is null");
} else {
console.log(x);
}
}
let x = 10;
let y;
let z = null;
show(x);
show(y);
show(z);
Output10 value not set value is null
With --strictNullChecks:
16:6 - error TS2345: Argument of type 'null' is not assignable to parameter of type 'number | undefined'.
16 show(z);
^
Summary
Given that T represents some type(s): T | null | undefined , T | null or just T are the same things, unless we use --strictNullChecks flag which prevents passing/assigning null when the target union type does not have 'null' type declaration (i.e. T | undefined or just T). Also using T | undefined or just T are always the same things.
Example ProjectDependencies and Technologies Used: |