Variable return types based on string literal type argument

Yes, you can use overload signatures to achieve exactly what you want:

type Fruit = "apple" | "orange"

function doSomething(foo: "apple"): string;
function doSomething(foo: "orange"): string[];
function doSomething(foo: Fruit): string | string[]
{
    if (foo == "apple") return "hello";
    else return ["hello", "world"];
}

let orange: string[] = doSomething("orange");
let apple: string = doSomething("apple");

Trying to assign doSomething("apple") to orange would yield a compile-time type-error:

let orange: string[] = doSomething("apple");
 // ^^^^^^
 // type 'string' is not assignable to type 'string[]'

Live demo on TypeScript Playground

It is important to note that determining which overload signature was used must always be done in the function implementation manually, and the function implementation must support all overload signatures.

There are no separate implementations per overload in TypeScript as there are in, say, C#. As such, I find it a good practice to reinforce TypeScript type-checks at runtime, for example:

switch (foo) {
    case "apple":
        return "hello";
    case "orange":
        return ["hello", "world"];
    default:
        throw new TypeError("Invalid string value.");
}

I have a better approach. use a generic which is then used as the type of the argument (So then you won't need to pass the generic manually and typescript will infer it automatically). Then you can use that type and choose the correct return type.

type Fruit = 'apple' | 'orange';
function doSomething<P extends Fruit>(foo: P): ({ apple: string; orange: string[] })[P] {
  if (foo === 'apple') return 'hello';
  return ['hello','world];
}
const x: string = doSomething('apple');
const y: string[] = doSomething('orange');

This way you can change the return type of your function based on the argument passed automatically.

Tags:

Typescript