Sometimes, we want to allow an optional parameter to be null in TypeScript.
In this article, we’ll look at how to allow an optional parameter to be null in TypeScript.
How to allow an optional parameter to be null in TypeScript?
To allow an optional parameter to be null in TypeScript, we can add the null
type in a union with other types.
For instance, we write
const foo = (bar: string | null) => {
console.info(bar);
};
foo("Hello World!");
foo(null);
to let us call foo
with the bar
parameter set to a string or null with the string | null
union type.
Then we call foo
as we do above without any errors.
Conclusion
To allow an optional parameter to be null in TypeScript, we can add the null
type in a union with other types.