user3038793
user3038793

Reputation: 23

How to pass conditionally a true or false to React boolean props with typescript?

I'm using Material UI library with React + Typescript.

When trying to pass conditional boolean as "button" prop of component I'm getting typescript error: Type 'boolean' is not assignable to type 'true'

I attached codesandbox link:

https://codesandbox.io/s/fragrant-worker-2l67x?file=/src/App.tsx

Upvotes: 2

Views: 1695

Answers (1)

Mosh Feu
Mosh Feu

Reputation: 29317

TLD'R

<ListItem
  button={item.isTitle ? undefined : true}
  divider={item.isTitle}
  key={item.text}
>

The explanation

In order to show a ListItem as button, you pass the button prop. If you don't want it to be button, you can pass false but it conflicts with the true type.

The other option to not show it as button is to not add the button prop at all. But how this helps you're asking? I have to set this prop for "not title" items.

So not passing a prop is like passing undefined. Since button is optional you can pass it as undefined instead of false.

https://codesandbox.io/s/so-67523398-lhgud?file=/src/App.tsx:1874-1914

Upvotes: 1

Related Questions