Conditional response types based upon function parameter

Viewed 33

I have a function that calls a method in a library, which returns different data depending on the parameters provided to the method.

A simplified example:

import aMethod from "aLib";

const aParam = "foo"; // or in other cases: "bar";
const response = aMethod(aParam);

If aParam is "foo", the response back from aMethod has a different shape than if I pass aParam as "bar". For example, the response from someParam === "foo" will have a shape like so:

type TFooResponse = {
  someObject: object;
  someString: string;
}

And if I pass "bar", then the shape of response will be:

type TBarResponse = {
  someArray: array;
}

How best should I handle stating ~ if aParam === "foo" use TFooResponse, else use TBarResponse?

1 Answers

I think you re looking for somehting like this:

type TType<T extends "foo" | "bar"> = {
    a: T,
    c: T extends "foo" ? TFooType : TBarType
}

Or for your exmaple:

function <T extends "foo" | "bar"> aMethod(aParam: T): T extends "foo" ? TFooType : TBarType {
    /**
     * 
     */
}
Related