How to conditionally pass optional props to component when we use React with Typescript?

Viewed 2032

When we use React with Typescript we can define optional props:

interface SomeProps {
  required: string
  optional?: number
}

const SomeComponent = ({ required, optional }: SomeProps): JSX.Element => { ...

When we use it later we can pass, or omit the optional property:

<SomeComponent required="abc" />
<SomeComponent required="def" optional={1} />

When we want to do it dynamically with React without Typescript we can pass undefined to optional property:

<SomeComponent required="ghi" optional={optionalValue ? optionalValue : undefined } />

But with Typescript that way doesn't work. Typescript transpiler will warn us that type number | undefined is not assignable to number. Of course we can wrap it in if statement and repeat SomeComponent usage but it's not the most elegant solution...

How can we conditionally pass optional props to component when we use React with Typescript?

UPDATE

I beg your pardon. I was wrong. This way of course works with Typescript as well. I didn't notice some internals in my code (which wasn't part of the question).

2 Answers
import React from 'react'

interface SomeProps {
  required: string
  optional?: number
}

const SomeComponent = ({ required, optional }: SomeProps) => null

const x = <SomeComponent required="abc" />
const y = <SomeComponent required="def" optional={1} />

const Foo = (optional?: number) =>
  <SomeComponent required="ghi" optional={optional ? optional : undefined} />

It works in Playground

You can add multiple types for the optional prop. In your case, the possible types are number & undefined. So you can define the optional prop as:

interface SomeProps {
      required: string
      optional?: number | undefined
    }
Related