Fix for Object is possibly null or undefined in typescript?

This post explains below things

  • The root cause of the error TS2533: Object is possibly ‘null’ or ‘undefined’?
  • Various methods to handle scenarios where Object is possibly null or Object is possibly undefined.

When converting TypeScript to JavaScript, the compiler detects instances where object or property values are null or undefined before compilation.

How do you fix the possibly null error object?

Typescript compiler throws an error when an object or its property is possibly null. To avoid this, Use one of the approaches before accessing the variable

  • Disabling the Compiler Option strictNullChecks (set to false) to bypass this error.
  • Manually checking for undefined using an if condition type guard.
  • Utilizing the Optional Chaining Operator (Question Mark ?).
  • Employing the non-null assertion operator (Exclamatory Mark !).
  • Leveraging nullish coalescing operators available in the latest JavaScript.

How do you fix the error object that is possibly undefined?

Similar to the possibly null error, the TypeScript compiler signals an error when accessing an object or its property values that could potentially be undefined.

To fix this, Use one of the approaches before accessing the variable

  • Disabling strictNullChecks (set to false) to skip this error.
  • Manually checking for null using an if condition type guard.
  • Using the Optional Chaining Operator (Symbol: Question Mark ?).
  • Employing the non-null assertion operator (Symbol: Exclamatory Mark !).
  • Utilizing nullish coalescing operators available in the latest JavaScript.

What causes error TS2533: Object is possibly ‘null’ or ‘undefined’“?

This error arises when an object property might yield null or undefined. It is a compile-time error triggered when the TypeScript compiler’s --strictNullChecks=true configuration flag is set.

For example, in the code snippet below, the object str is defined as a string array or undefined or null. Consequently, the str property may potentially hold null or undefined values.

let str: string[] | undefined | null;
let len: number = str.length; // Object is possibly 'null' or 'undefined'.

Attempting to access the length of a string object in the above code triggers Object is possibly ‘null’ or ‘undefined’ error during both compile-time and linting if configured.

Fix for Object is possibly ‘null’ or ‘undefined’

There are multiple solutions to avoid this.

  • disable strictNullChecks in ts configu.json

    This solution is not fixing an error, but skipping an error at compile time by setting the compiler flag.

    In typescript applications, open tsconfig.json and set strictNullChecks to false.

    For example, in Angular applications, add this to angularCompilerOptions in tsconfig.json

    {
      "angularCompilerOptions": {
        "strictNullChecks": false,
      }
    }
    

    In react typescript applications, open tsconfig.jsonand change strictNullChecks to false in compilerOptions

    {
      "compilerOptions": {
              "strictNullChecks": false
    
      }
    }
    

    The same code above works in Vue Typescript, and node typescript applications.

  • Manually check null or undefined using the if condition

    In this case, You can use and if conditional expression to avoid a null or undefined check

    We have to handle null or undefined checks using a variable in if the expression

    This checks for string objects that exist or null and undefined values. It only calls the length method if a string object exists.

    let str: string[] | undefined|null
    
    if (str) {
      let len number = str.length; // Object is possibly 'null' or 'undefined'.
    }
    
  • Fix with Optional Chaining operator

    Optional Chaining is introduced in the typescript 3.7 version. used for variables that tell the compiler that variables are optional. The optional Chaining operator is ? and appended to a variable(variable?) as below

    let str: string[] | undefined | null;
    let lenb: number = str?.length;
    
  • Using a non-null assertion operator

    The non-null assertion operator symbol is an Exclamatory symbol(!) and appended to a variable to avoid null or undefined.

    This tells the typescript compiler that the variable should never be null or undefined

    let str: string[] | undefined|null
    let len: number =  str!.length  ;
    
  • Fix with nullish coalescing operators

    The nullish coalescing operator symbol is ?? introduced in the latest Javascript ES2021.

    the nullish coalescing operator (??) returns the right-hand operand when the left-hand operand is null or undefined.

    let str: string[] | undefined | null;
    function getLength(str: string[] | "") {
      return str.length;
    }
    let len: number = getLength(str ?? "");
    

Conclusion

This post explored handling scenarios where an object is possibly null or undefined in TypeScript along with various solutions.