DEV Community

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

Posted on • Edited on

8 2

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)

typescript

11 Tips That Make You a Better Typescript Programmer

1 Think in {Set}

Type is an everyday concept to programmers, but it’s surprisingly difficult to define it succinctly. I find it helpful to use Set as a conceptual model instead.

#2 Understand declared type and narrowed type

One extremely powerful typescript feature is automatic type narrowing based on control flow. This means a variable has two types associated with it at any specific point of code location: a declaration type and a narrowed type.

#3 Use discriminated union instead of optional fields

...

Read the whole post now!

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay