Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Typescript double return type object check

interface TypeOne {
  name: string;
  typeOneProp: any;
}

interface TypeTwo {
  name: string;
  typeTwoProp: any;
}

async function foo(): Promise<TypeOne | TypeTwo> {
   return this.service.get();
}

async function bar(): Promise<any> {
   const data = await foo();
   
   if(data?.typeOneProp) { // errors shown below
      return data.typeOneProp;
   }
}

Property 'typeOneProp' does not exist on type 'TypeOne | TypeTwo'.

Property 'typeOneProp' does not exist on type 'TypeTwo'. ts(2339)

how can i show typescript which return type foo() had?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

already tried Object.keys to see if typeOneProp exists but data remains as TypeOne | TypeTwo

data intelisense only shows name as a property sugestion as is a common property between both types

// package.json
"typescript": "^4.4.4"

>Solution :

Use the in operator to check if the property exists on the object (TS playground):

if('typeOneProp' in data) {
  return data.typeOneProp;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading