Home > Mobile >  TypeScript overload function signature with boolean parameter with dependant return type
TypeScript overload function signature with boolean parameter with dependant return type

Time:11-14

I would like to call a function with return type based on input boolean parameter, so it returns some type if parameter is false and some other type if parameter is true. I thought overloads are perfect for this case, but TypeScript won't let me use them:

  hello(foo: false): ''
  hello(foo: true): 'bar' {
    if(foo) {
      return 'bar'
    } else {
      return ''
    }
  }

Because I get This overload signature is not compatible with its implementation signature.

Should I use something else, modify this code or just switch to multiple functions with different names and similar behaviour?

CodePudding user response:

Your attempt to create an overload function is incorrect. Each variant must be compatible with the underlying implementation

In your code:

  • underlying implementation accepts only true and returns bar
  • thus hello(foo: false): '' is not compatible with it
function hello(foo: true): 'bar'
function hello(foo: false): ''
function hello(foo: boolean): '' | 'bar' {
  if(foo) {
    return 'bar'
  } else {
    return ''
  }
}

const aFoo = hello(true);
const anEmptyString = hello(false);
  • Related