DEV Community

Cover image for Dependent Props In React Typescript
Daniel Bellmas
Daniel Bellmas

Posted on • Updated on

Dependent Props In React Typescript

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:
Property 'description' does not exist on type 'ICardBase & (ICard1 | ICard2)'

Property 'footer' does not exist on type 'ICardBase & (ICard1 | ICard2)'

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:

Manual interfaces

But a cleaner way is to create a utility type 🔥, like so:

Never type utility

The Never util takes every prop and makes its type never.

It allows for scalable code.
Naturally, the component starts small until the product/UX team wants it to be a bit different...

Types with the Never util

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).

Error shown by typescript to make sure we are using the component correctly

This protects us, the developers, from mixing up between the two separate (but similar) cards. 🦾

Top comments (0)