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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *