Null-able types are all about typing a variable value that can either hold a valid value of a specific type or be NULL or UNDEFINED.
How to handle them in typescript? so writing robust and error-free TypeScript code.
- Declare Null-able Types: [using the union operator (
|
)]:
let name: string | null;
let age: number | undefined;
- Checking for Nullable Values: [use type guards]
if (name !== null) {
console.log(name.toUpperCase());
}
- Optional typing: [use Optional chaining]:
console.log(age?.toFixed(2));
- Assigning Nullable Values: [assigned null or undefined explicitly]:
name = null;
age = undefined;
- Nullish Coalescing Operator (
??
):
- It returns the right-hand operand if the left-hand operand is null or undefined.
let result: string;
let nullableValue: string | null = null;
// Using nullish coalescing operator
result = nullableValue ?? "Default Value";
console.log(result); // Output: "Default Value"
By understanding how to handle nullable types in TypeScript, you can write more robust and error-resistant code that gracefully handles nullable values.
Article on Linkedin: https://www.linkedin.com/posts/taricov_typescript-developercommunity-softwareengineering-activity-7170098531318284288-hoIj?utm_source=share&utm_medium=member_desktop
Top comments (0)