Typescript Conditional Return Type Problem

52 views Asked by At

I am trying to use a conditional return type for a function to either return a string or a tuple, depending on the value of an option passed as an argument. For some reason, the Typescript compiler is complaining.

function fetchFromDB() {
  return 'Apple';
}

function fetchRelatedFromDB() {
  return ['Banana', 'Cherry'];
}

type Options = {
  includeRelated?: boolean;
};

type ConditionalReturn<T extends Options> = T extends {
  includeRelated: true;
}
  ? [string, string[]]
  : string;

export function find<T extends Options>(
  options: T
): ConditionalReturn<T> {
  const fruit = fetchFromDB();

  if (options.includeRelated) {
    const related = fetchRelatedFromDB();
    return [fruit, related];
  }

  return fruit;
}

const stringResult = find({});

const tupleResult = find({ includeRelated: true });

See the following playground example...

Playground Example

Line 26 and 29 both show an error. I have used conditional return types before, but this example is stumping me. I appreciate any help.

Here is an example of where I did get conditional return types working.

Working Example

1

There are 1 answers

2
mikrowdev On

Not sure if it's your desired output, but you could use a "strange" way to achieve this through type assertion forcing the generic type for each return output as follows


export function find<T extends Options>(options: T): ConditionalReturn<T> {
  const fruit = fetchFromDB();

  if (options.includeRelated) {
    const related = fetchRelatedFromDB();
    return <ConditionalReturn<T>>[fruit, related];
  }

  return <ConditionalReturn<T>>fruit;
}