← Back
react typescript

Optional parameters and undefined values

In typescript, it's possible to type values that can be undefined:

function sayHello (name: string | undefined) { ... }

But this is roughly equivalent to optional parameters:

function sayGoodbye (name?: string) { ... }

Today I've realised there's a big difference: in the optional parameters version we can omit the parameters:

sayGoodbye('Mars')
sayGoodbye(undefined)
sayGoodbye()

It's not the case with undefined values:

sayHello('Mars')
sayHello(undefined)
sayHello()

This is relevant in React (how not!) because we can force to send the props even if they are undefined.

This is optional props:

type Props = {
name?: string
}
const Hello: React.FC<Props> = ({ name }) => ...

<Hello name="world" />
<Hello name={undefined} />
<Hello />

And this props with undefined:

type Props = {
name: string | undefined
}
const Bye: React.FC<Props> = ({ name }) => ...

<Bye name="world" />
<Bye name={undefined} />
<Bye />