Home > OS >  Typescript make function return different types for different inputs
Typescript make function return different types for different inputs

Time:09-04

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.

Thanks in advance for any help you guys can provide!

CodePudding user response:

Try function overload:

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

CodePudding user response:

you should use generics like this:

function example<Type>(input: Type): Type {
  return input ? "string" : 0;
}

then:

let output = example<string>(true);
  • Related