TransWikia.com

Typescript - How to solve " Type 'undefined' is not assignable to type 'XXXX' "?

Stack Overflow Asked by Paritosh M on February 16, 2021

I have interface defined with some properties. When trying to access the service I am getting this error – Type ‘undefined’ is not assignable in displayfile at this.isOpen. I need help to resolve this error.

Note – I can not set values in config file such as "strictNullChecks":false

Interface

export interface DataFile {
  file?: DataFile[];
  location: string;
}

Typescript class


  isOpen?: DataFile;

  Scan(aero: string, TeamClass: string) {
    if (TeamClass === 'Hawkins') {
      if (this.redService.name.file && this.redService.name.file.length > 0) {
        this.isOpen = this.redService.name.file.filter((data: DataFile) => data.location == aero[0])[0];
      }
    }
    
    this.displayfile(this.isOpen).then(async () => {  ----->>>>>> Error at this.isOpen
            //rest of the functionality
        }
      }
    });
  }

I am getting error-

 Argument of type 'DataFile | undefined' is not assignable to parameter of type
'DataFile'.
  Type 'undefined' is not assignable to type 'DataFile'.

One Answer

By setting isOpen with a question mark it picks up two types: one that's DataFile (your type) and undefined. That's the main reason why Typescript is reporting an error.

To resolve it you have two options:

  • Check if isOpen populates with data, i.e.:
if (!isOpen) { /* do something */ }
...rest of code
  • Prepend isOpen with a ! (i.e., this.isOpen!) that way you force the type to not be undefined. Not recommended because if it is indeed undefined you'll run into errors inside your this.displayfile function.

Reference on the question mark operator here: https://www.geeksforgeeks.org/why-use-question-mark-in-typescript-variable/

Correct answer by jayg_code on February 16, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP