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?
CodePudding user response:
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
, andBoolean
(starting with capital letters) are legal, but refer to some special built-in types that will very rarely appear in your code. Always usestring
,number
, orboolean
for types.