Home > OS >  Typescript: conditional return type not working
Typescript: conditional return type not working

Time:10-31

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

CodePudding user response:

Why does TSC raise the error

I believe you need to specify the returned value explicitly.

const test = (flag: boolean): typeof flag extends true ? 'yes' : 'no' =>
   (flag === true ? 'yes' : 'no') as typeof flag extends true ? 'yes' : 'no';

Or either using generics:

const test = <T extends boolean>(flag: T): T extends true ? "yes" : "no" =>
   (flag === true ? "yes" : "no") as T extends true ? "yes" : "no";

CodePudding user response:

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"
}
  • Related