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

I am new to TypeScript and I cannot figure out which type to assign to the returning value of a function which can be a string or boolean

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:

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

    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.

>Solution :

You can use a union | like this…

    var getValue = (myVal: number):boolean | string => {
        if(myVal > 5){
            return true;
        }
        return "200 OK";
    }
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