Handling
Optional Chaining ✅
Nullish Coalescing
When you have the option, using a default value for variables that might be undefined is really helpful. Typically we use the logical OR operator (**||**
) to assign the default value.
const messageInputValue = document.getElementById("messageInput")?.value || "Alex";messageInputValue; // const messageInputValue: string;
The only problem with this approach is it checks against falsy values, not just **null**
and **undefined**
. That means when our **#messageInput**
field is empty, it will still give us the default value since empty **string**
is falsy.
The Nullish Coalescing operator solves this by only checking if a value is **null**
or **undefined**
. It works the same way as the logical OR, but with two question marks (**??**
) instead of two vertical bars.
const messageInputValue = document.getElementById("messageInput")?.value ?? "Alex";messageInputValue; // const messageInputValue: string;
Non-null Assertion (only TS)
Sometimes, you just know better than the type checker. If you positively know that a particular value or property is not **null**
or **undefined**
, you can tell the type checker using the Non-null Assertion operator (**!.**
), which looks a lot like the Optional Chaining operator. Using this operator essentially tells the type checker "There's no way this property could possibly be **null**
or **undefined**
, so just pretend like it's the correct type."
const messageInputValue = document.getElementById("messageInput")! .value;messageInputValue; // const messageInputValue: string;
Notice we don't have to add a default value. TypeScript trusts that we know what we are doing and will give us the value with the appropriate type, no questions asked. Be aware that, unlike the other two operators, the Non-null assertion operator only exists in TypeScript. If you tried using it in JavaScript, it would throw a syntax error.
Remember, any time we override the default behavior of the type checker, we run the risk of introducing type errors that the type checker cannot catch for us. Using the Non-null Assertion operator removes the type safety which we wanted TypeScript to give us in the first place, so if it is at all possible, handle **null**
and **undefined**
properties with one of the other methods before resorting to Non-null Assertions.