Categories
TypeScript Answers

How to allow an optional parameter to be null in TypeScript?

Spread the love

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.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.