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

Multiple return type(Array<string> | Boolean) for arrow function

I have an arrow function in a class that returns either array or boolean:

class A{

   myfunction=(val:number):Array<string>|Boolean=>{
     return number>1000?true:["jack","robin","harry"];
   }
}

and I want to call the function as:

const myclass=new A();

const arr=myclass.myfunction(10);

if(typeof arr==="boolean"){
  console.log("dami");
}else{
   if(arr.indexOf("harry")>0){
          ##here at indexOf i get an error :Property 'indexOf' does not exist on type 'Boolean | string[]'.
     console.log("we found harry");
   }
}

Calling indexOf gives an error saying : Property 'indexOf' does not exist on type 'Boolean | string[]'. What am I doing wrong here?

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

>Solution :

Your return type should refer to the primitive boolean type:

Array<string> | boolean // or string[] | boolean

And not the object Boolean type:

Array<string> | Boolean

As the TypeScript handbook notes:

The type names String, Number, and Boolean (starting with capital
letters) are legal, but refer to some special built-in types that will
very rarely appear in your code. Always use string, number, or boolean
for types.

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