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 make function return different types for different inputs

I am working on a Typescript project and have a function that returns one value when an input is true and another one when an input is false. The problem is that these two possible return values are two different types, and I have no idea how to properly have Typescript handle that.

The function is sort of like this:

function example(input: boolean): number | string {
  return input ? "string" : 0
}

As you can see, I tried using a union type, but this just forces me to do a type check later, which is not the behavior that I want. I am trying to get it so when input is true, the return type will be string, and when input is false, the return type will be number. So far everything that I have tried has not been working.

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

Thanks in advance for any help you guys can provide!

>Solution :

Try function overload:

function example(input: true): string;
function example(input: false): number;
function example(input: boolean): number | string {
  return input ? "string" : 0
}
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