schneck
schneck

Reputation: 10827

Typing a factory function

I have a runtime-constructed list of functions which are initialized with an argument, and return different things:

 mythings: [
   param => ({foo: param, bar: 2}),
   param => ({baz: param, qux: 4}),
 ]

Now I want to write a factory function to create a subset of these things, like:

const createThings = (things) => things.map(thing => thing("param"));

I'm struggling typing the factory function. My recent attempt looks like this:

// MyCreator?

const createThings = <T>(things: MyCreator<T>[]) =>
  things.map(thing => thing("param"));

But this attempt does not work. Any idea?

Upvotes: 1

Views: 91

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249536

You can use mapped array/tuples to extract the return type from each item in the array:

const mythings = [
   (param: string) => ({foo: param, bar: 2}),
   (param: string) => ({baz: param, qux: 4}),
 ]
type AllReturnTypes<T extends Array<(...a: any[])=> any>> = { 
    [P in keyof T]: T[P] extends (...a: any[])=> infer R?R:never
}

const createThings = <T extends Array<(...a: any[])=> any>>(things: T): AllReturnTypes<T> =>
  things.map(thing => thing("param") )as any; // assertion necessary unfortunately 

createThings(mythings) // ({ foo: string; bar: number; } | { baz: string; qux: number; })[]

You can also make myThings a tuple type so you get more acurate types for each index in the result:

function tuple<T extends any[]>(...a: T) {
    return a;
}
const mythings = tuple(
    (param: string) => ({ foo: param, bar: 2 }),
    (param: string) => ({ baz: param, qux: 4 }),
)

let r = createThings(mythings) // [{ foo: string; bar: number; }, { baz: string; qux: number; }

Or in typescript 3.4 you can use as const:

const mythings = [
    (param: string) => ({ foo: param, bar: 2 }),
    (param: string) => ({ baz: param, qux: 4 }),
] as const

Upvotes: 3

Related Questions