I’m making a React component which accepts an array of other React components with their props.
type Components = [ComponentType, Props][]
How can I write this, so typescript will understand that Props object should match given Component props?
Thanks.
UPD, Basically a function takes an array of [fn, args] tuples and calls each fn with the corresponding args. How do I write the signature of that function so that the tuples are type-safe correct fn/arg pairings?
2
Answers
You can do this, although it’s a little complicated and in its current implementation its a bit more fragile than I’d like. I’ve abstracted the type logic into a helper type:
We can define a couple of Component/props pairs to test this:
and then test it:
This isn’t perfect. In particular there are two areas you could potentially improve this: better intellisense (somebody who passes an invalid pair will just get "type blah is not assignable to type ‘never’" which isn’t a great error message. The second is that if you try to pull out the pairs into a variable you’ll see an issue with the inference, although that can be mitigated a bit by using
satisfies
:Note that this is still type safe despite the
any
s: if you pass an invalid pair you’ll get an error.Another issue with this solution is that if you try to type the array of pairs as a tuples using
as const
you’ll see an error relating to thereadonly
ness ofas const
. I’ll keep trying to clean this up, although maybe somebody more clever can give a better solution.Playground
Try to use TypeScript generics to define a type for your array of components along with their corresponding props. Here’s how you can do it:
The
Props
type uses a conditional type to infer the props type of a given component type. The Components type takes an array of component-prop pairs and ensures that each component’s props match the specified props type.You can then use the
Components
type to define your array of components along with their props.