Nullish Coalescing in TypeScript: How to Use the Nullish Coalescing Operator
TypeScript is a powerful language that adds type annotations to JavaScript, making it more reliable and easier to maintain. One of the features introduced in TypeScript 3.7 is the nullish coalescing operator, which is a shorthand for checking whether a value is null or undefined before using a default value. In this post, we'll explore how to use the nullish coalescing operator in TypeScript, and how it can help you write more robust code.
The nullish coalescing operator (??) is a new operator in TypeScript that allows you to define a default value for a variable if it is null or undefined. Here's an example:
const foo = null ?? 'default'; // foo === 'default'
const bar = undefined ?? 'default'; // bar === 'default'
const baz = 'value' ?? 'default'; // baz === 'value'
In this example, the nullish coalescing operator checks whether the value of the variable is null or undefined. If it is, it returns the default value 'default'. If the value of the variable is not null or undefined, it returns the value of the variable itself.
Note that the nullish coalescing operator only checks for null or undefined values, not falsy values like 0 or ''. If you want to check for falsy values as well, you can use the logical OR operator (||) instead.
The nullish coalescing operator is a handy shorthand for checking whether a value is null or undefined before using a default value. This can help you write more concise and readable code, especially when dealing with optional parameters or default values.
Consider the following example:
function printMessage(message?: string) {
console.log(message || 'Hello, world!');
}
In this example, the printMessage function takes an optional parameter message, which defaults to 'Hello, world!' if it is not provided. However, the logical OR operator (||) used here will also return the default value if message is falsy, which is not what we want. To fix this, we can use the nullish coalescing operator instead:
function printMessage(message?: string) {
console.log(message ?? 'Hello, world!');
}
Now, the printMessage function will only use the default value if message is null or undefined, which is the behavior we expect.
The nullish coalescing operator is a useful addition to TypeScript that can help you write more concise and readable code. By using the nullish coalescing operator, you can define default values for variables and parameters without worrying about falsy values. If you're not already using the nullish coalescing operator in your TypeScript projects, give it a try and see how it can simplify your code.