Search code examples
typescripttsc

Typescript: conditional return type not working


I have a function whose return type should depend on the provided arguments.

const test = (flag: boolean): typeof flag extends true ? "yes" : "no" => {
  if (flag === true) {
    return "yes"
  } else {
    return "no"
  }
}

Why does TSC raise the error Type '"yes"' is not assignable to type '"no"'.ts(2322) for the line return "yes"?

Using Typescript 4.8.4


Solution

  • For this, you can use a feature called overloading, where you define the possible inputs and outputs for the function.

    function test(flag: true): "yes";
    function test(flag: false): "no";
    
    function test(flag: true | false): "yes" | "no" {
      return flag === true ? "yes" : "no"
    }