I want to build some kind of FactoryFactory
: Basically a generic function that returns a factory function. Writing the function itself is simple, but I can't figure out how to do the TypeScript typings for it.
The function should be used like this:
const stubFactoryFunction = (...props) => (...values) => ({ /* ... */ });
const factory = stubFactoryFunction("prop1", "prop2");
const instance = factory("foo", 42);
console.log(instance); // { prop1: "foo", prop2: 42 }
At first I tried to provide the value types as an array:
type FactoryFunction<T extends any[]> =
<K extends string[]>(...props: K) =>
(...values: T[number]) =>
{[key in K[number]]: T[number]}
But this will result in { prop1: string | number, prop2: string | number}
, because the type doesn't match the array indexes.
Next I tried to provide the whole object as generic type:
type FactoryFunction<T extends {[key: string]: any}> =
(...props: (keyof T)[]) =>
(...values: ???) =>
T
And here I got a similar problem: values
must somehow match the order of props
.
Is this possible at all?
Bonus 1: Don't allow duplicate props.
Bonus 2: Enforce the provide all non-optional props from T
.
length
property to enforce the same length ofP
andV
! – Pejoration