#Union of return types of arb number of input functions

1 messages · Page 1 of 1 (latest)

earnest wigeon
#

I have something like this:

type Foo<TOut> = ( a: number ) => TOut;

function bar<TOut> ( ...fs: Foo<TOut>[] ): Foo<TOut>;

const fa = ( a: number ) => 1 as const;
const fb = ( a: number ) => 'b' as const;
const fc = ( a: number ) => true as const;

Is it possible to modify the type definition of bar so it would automatically infer ReturnType of the returned function as a union of ReturnTypes of all input functions (unknown in case of 0 input functions)?

Currently I have to provide a hint like this:

const fr = bar(
  fa as Foo<1|'b'|true>,
  fb,
  fc
  );
slim shoalBOT
#
angryzor#9490

Preview:```ts
type Foo<TOut> = (a: number) => TOut

declare function bar<Fns extends Foo<unknown>[]>(
...fs: Fns
): ReturnType<Fns[number]>

const fa = (a: number) => 1 as const
const fb = (a: number) => "b" as const
const fc = (a: number) => true as const
...```

rigid ivy
#

@earnest wigeon

earnest wigeon
# rigid ivy <@125171658469277696>

Awesome! Thank you!
I forgot my Foo actually returns a wrapped result, but I was able to adapt this solution for that easily.
And it even works with Fns extends [...FooA<TOut>, FooB<TOut>]

#

!resolved

earnest wigeon
#

Actually, it might be missing ( a: number ) => ReturnType<Fns[number]> in place of ReturnType<Fns[number]> here.
I didn't notice it because my final solution looks like

function bar<
  Fns extends Foo<unknown>[],
  TOut = Fns extends Foo<infer T>[] ? T : never
> (
  ...fs: Fns
): Foo<TOut>;

(Later update: run into complications with real code.
These smarts often have limitations - trying to infer some part of type information, they block type inference in other ways...)