Typescript Nullable<T>
Typescript supports two ways of telling if a value is missing or uninitialized. Usually, it doesn't matter if its null
or undefined
since people have different approaches and might use one or both of them. A common way to check if a value is missing
is:
if (value == null) {
...
}
The loose comparison with null
checks for both null
and undefined
. Since we can operate on both types, one might want to get rid of errors like type null/undefined is not assignable to type | null/undefined...
by introducing the following type:
export type Nullable<T> = T | null | undefined;
Now, instead of a long repetitive declaration:
function (data: string | null | undefined)
the short and clean version can be used:
function (data: Nullable<string>)
Example:
class Formatter {
insertUndescores(data: Nullable<string>): string {
return data?.split('').join('_') ?? '';
}
}
const formatter = new Formatter();
formatter.insertUndescores(null);
formatter.insertUndescores(undefined);
formatter.insertUndescores('An example');