My team has created typescript types definitions for an API that we're using, so we aren't able to touch the source code, just the definitions.
We have a function called add that essentially adds one or more react components to the main program. The props property of the object should depend on the component type listed on the component property.
It looks like this:
add(arg1, arg2, {
//some other args
children: [{
id: string1,
//BackButton can be a functional or class-based component
component: BackButton,
//BackButtonProps will be defined within BackButton
props: BackButtonProps
},
{
id: string2,
//SkipButton can be a functional or class-based component
component: SkipButton,
//SkipButtonProps will be defined within SkipButton
props: SkipButtonProps
}
]
});
For reference, there is an alternate (overloaded) version of the function that only adds one component instead of multiple that I've been able to figure out the typescript for. It looks like this:
add<T>(
id: string,
component: ComponentType<T>,
props: T
): void;
My question is this -- since the number of children components is unknown, how can I use a generic on the add function so that all the children components are correctly typed (the props and component properties match up)?
A generic signature of
addwould look like this.The generic type
Twould store a tuple where each element is a react component. For each element with the indexKof the passed array, thecomponenttype would be used as the type inT[K]and thepropstype would have to beReact.ComponentProps<T[K]>.Let's see this in action:
Playground