Home > Enterprise >  I am new to TypeScript and I cannot figure out which type to assign to the returning value of a func
I am new to TypeScript and I cannot figure out which type to assign to the returning value of a func

Time:01-14

TypeScript: Given value of function is a number but returning value can be a string or boolean.

In this case the returning value type is Any which I do not want to use:

    var getValue = (myVal: number) => {
        if(myVal > 5){
            return true;
        }
        return "200 OK";
    }

In this case the returning value type is Boolean which cause error for the string:

    var getValue = (myVal: number):boolean => {
        if(myVal > 5){
            return true;
        }
        return "200 OK";
    }

In this case the returning value type is String which cause error for the boolean:

    var getValue = (myVal: number):string => {
        if(myVal > 5){
            return true;
        }
        return "200 OK";
    }

I have used the type Any in this scenario but as it is not a good practice so I just wanted to know which type can be used instead of Any.

CodePudding user response:

You can use a union | like this...

    var getValue = (myVal: number):boolean | string => {
        if(myVal > 5){
            return true;
        }
        return "200 OK";
    }
  • Related