Im having some trouble defining a generic for this specific scenarion.
I have multiple React components defined like this:
type ComponentFunction<T> = (props: T) => void;
interface FooProps {
bar: string;
}
const Foo: ComponentFunction<FooProps> = ({ bar }) => {};
and I want to have an interface
that would look something like this:
interface Component<T> {
element: ComponentFunction<T>;
props: T;
}
what I would like is to have an array of those components without having to define the generic for each and every one of them. It would just be automatically "detected" from the passed element
, for example:
const components: Component<?>[] = [
{
element: Foo,
props: {
bar: "bar"
}
},
...
]
Is this even possible?
Edit 1:
Replaced React.FC
with a more generic example ComponentFunction
.
Solution 1:
const componentArray = <T extends any[]>(array: { [I in keyof T]: Component<T[I]> }) => array;
const components = componentArray([
{
element: Foo,
props: {
bar: "string"
}
},
...
]);
Solution 2:
type SomeComponent = <R>(cb: <T>(component: Component<T>) => R) => R;
const someComponent = <T,>(component: Component<T>): SomeComponent => cb => cb(component);
const components: SomeComponent[] = [
someComponent({ element: Foo, props: { bar: "string" } }),
...
];
Thanks to @jcalz for providing the solutions.