Dependent Props In React Typescript
Daniel Bellmas
Posted on September 23, 2022
A dependent prop is a prop that should only be set when another prop has a specific value.
In the example below we can see one use case (click on Open Sandbox
to see the code):
Here we have two options of the same generic card.
- Card1 - has only two props:
title
,description
- Card2 - has only two props:
title
,footer
In order to use the full power of typescript when writing generic components, we need to give typescript the specific options that are acceptable to us.
We might think that passing Card1 | Card2
to the Props
type is enough, but when we do that typescript will show us the following errors:
And that's because we can only have one or the other, and so if we're currently rendering Card1
then we won't have the footer
prop, and vice versa, when we render Card2
we won't have the description
prop.
To solve this, we need to still pass the missing prop as never
(undefined
will work as well but never
indicates that the prop will never occur).
We could do it manually like so:
But a cleaner way is to create a utility type 🔥, like so:
The
Never
util takes every prop and makes its typenever
.It allows for scalable code.
Naturally, the component starts small until the product/UX team wants it to be a bit different...
By doing all that we get a better experience using the generic component - typescript will throw errors when we are incorrectly using it, (for example, passing both footer
and description
- an impossible situation).
This protects us, the developers, from mixing up between the two separate (but similar) cards. 🦾
Posted on September 23, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.