简体   繁体   中英

In TypeScript, can I infer a mapped type from function overloads?

Given these overloads:

function f(p: 'a'): 'x';
function f(p: 'b'): 'y';
function f(p: 'c'): 'z';

Can I somehow infer this type from f ?

type M = {
  'a': 'x';
  'b': 'y';
  'c': 'z';
}

Found one way, though it is a bit cumbersome and can only handle a limited number of overloads.

interface Test {
  f(p: 'a'): 'x';
  f(p: 'b'): 'y';
  f(p: 'c'): 'z';
};

type MapArgumentToReturn<F> =
    F extends { (a: infer A): infer AR; (b: infer B): infer BR; (c: infer C): infer CR } ? [A, AR]|[B, BR]|[C, CR] :
    F extends { (a: infer A): infer AR; (b: infer B): infer BR } ? [A, AR]|[B, BR] :
    F extends { (a: infer A): infer AR } ? [A, AR] :
    never;

type TupleToObject<T extends [string, any]> = { [key in T[0]]: Extract<T, [key, any]>[1] };

type Result = TupleToObject<MapArgumentToReturn<Test['f']>>;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM