DEV Community

Cover image for TypeScript (2): Handling Nullable Types (5 quick ways)
Taric Ov
Taric Ov

Posted on

TypeScript (2): Handling Nullable Types (5 quick ways)

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.

  1. Declare Null-able Types: [using the union operator (|)]:

   let name: string | null;
   let age: number | undefined;

Enter fullscreen mode Exit fullscreen mode
  1. Checking for Nullable Values: [use type guards]

   if (name !== null) {
       console.log(name.toUpperCase());
   }

Enter fullscreen mode Exit fullscreen mode
  1. Optional typing: [use Optional chaining]:

   console.log(age?.toFixed(2));

Enter fullscreen mode Exit fullscreen mode
  1. Assigning Nullable Values: [assigned null or undefined explicitly]:

   name = null;
   age = undefined;

Enter fullscreen mode Exit fullscreen mode
  1. 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"

Enter fullscreen mode Exit fullscreen mode

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)