TypeScript error “Object is possibly ‘null’ or ‘undefined'”

Why Did You Get That Error?

Because TypeScript detected your property value can be null or undefined. In TypeScript, this feature called “strict null checks“. Let’s see the following example.

class Example {

  doSomething(): void {
    const username = 'David' as string | undefined;
    const length = username.length;
    //             ~~~~~~~~
    // Error: Object is possibly 'undefined'.
  }

}

As you can see, TypeScript throws error “Object is possibly ‘undefined’” for username object.

 

 

How To Fix That Error?

In order to fix that error, we have some ways as below:

 

1. Disable “strict null checks”

Open tsconfig.json and add "strictNullChecks": false to angularCompilerOptions

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

 

2. Use IF condition

You can use IF condition to check datatype of property/variable.

class Example {

  doSomething(): void {
    const username = 'David' as string | undefined;
    // use IF condition, 
    // the error gone away! :)
    if (typeof username === 'string') {
      const length = username.length;
    }
  }

}

 

 

 

3. Add ! (exclamation mark) after a property/variable name

You can add ! (exclamation mark) after a property/variable name. This feature is called “Non-null assertion operator“, basically it means that when you add the exclamation mark after a property/value, you are telling TypeScript that you are certain that value is not null or undefined.

class Example {

  doSomething(): void {
    const username = 'David' as string | undefined;
    // add ! (exclamation mark) after the property/variable, 
    // the error gone away! :)
    const length = username!.length;
  }

}

 

4. Add ? (question mark) after a property/variable name

You can add ? (question mark) after a property/variable name. It is to mark the property/variable as optional.

class Example {

  doSomething(): void {
    const username = 'David' as string | undefined;
    // add ? (question mark) after the property/variable, 
    // the error gone away! :)
    const length = username?.length;
  }

}

 

 

 

 

developer.mozilla -  Оператор опциональной последовательности