bingles
bingles

Reputation: 12203

TypeScript - function to map union type to another union type based on discriminator

I have 2 discriminated union types that use the same discriminator field + values. I'm trying to write a function that can map 1 to the other based on the discriminator.

e.g.

Input type:

type InA = {
    type: 'a',
    data: string
};

type InB = {
    type: 'b',
    data: number
};

type In = InA | InB;

Output type:

type OutA = {
    type: 'a',
    data: Object
};

type OutB = {
    type: 'b',
    data: Array<number>
};

type Out = OutA | OutB;

Mapping function

// This is the function I'd like to have a better type signature
// for inferring output type based on input type
function map<In, Out>(
    in: In
): Out {
   // do something
}

Usage

// I want the compiler to infer that this is OutB based on the InB
let result = map({ type: 'b', value: 999 });

Is there a way to write the function signature for map such that this will work?

UPDATED AFTER ANSWERED I was able to use a modified version of @titian-cernicova-dragomir answer. Here's the general idea + some additional context as to how I'm using it:

/** Http Request types **/

type RequestA = {
    type: 'names',
    url: '/names'
};

type RequestB = {
    type: 'numbers',
    url: '/numbers'
};

type Request = RequestA | RequestB;

/** Response types **/

type ResponseA = {
    type: 'names',
    data: Array<string>
};

type ResponseB = {
    type: 'numbers',
    data: Array<number>
};

type Response = ResponseA | ResponseB;

/** Helper from accepted answer */
type GetOut<T, A> = T extends { type: A } ? T : never;

/** Generic function for fetching data */
export function fetchData<
    Req extends Request,
    Res extends GetOut<Response, Req['type']>
    >(request: Req): Promise<Res> {
    return fetch(request.url)
        .then(response => response.json())
        .then(data => {
            return <Res>{
                type: request.type,
                data
            }
        });
}

// compiler knows that this is of type Promise<ResponseA> based on
// type discriminiator
let names = fetchData({
    type: 'names',
    url: '/names'
});

// compiler knows that this is of type Promise<ResponseB> based on
// type discriminiator
let numbers = fetchData({
    type: 'numbers',
    url: '/numbers'
});

Upvotes: 5

Views: 873

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249676

You can use conditional types to do this. First we use a conditional type to extract the actual string literal type that is passed as an argument (we will call it A). Then using A we will filter Out to get the type from the unon that extends { type: A }.

type GetOut<T, A> = T extends { type : A} ? T: never; 
function map2<TIn extends In>(inParam: TIn) : TIn extends { type: infer A } ? GetOut<Out, A> : never {
    return null as any;
}

let resultA = map2({ type: 'a', data: '999' }); // result is OutA
let resultB = map2({ type: 'b', data: 999 }); // result is OutB

Playground link

Upvotes: 2

Related Questions