typescriptreact-typescriptobject-destructuringnullish-coalescing

Can you destruct an object and have nullish coalescing for potential undefined constants?


I use React, so I have a props object, for example:

const props: { id: number, name?: string} = { id: 1 }; // not defining the `name`
const { id, name } = props; // here the `const name` becomes undefined forever and even if I use the defaultProps pattern of React, Typescript still shows warnings for potential undefined

Is there any way to use nullish coalescing while destructing the object? I cannot use this (due to ESlint rule defined by the team):

const name = props.name ?? 'placeholder name';

Solution

  • You can assign a default value if the name is undefined, without using optional chaining:

    const { id, name = 'placeholder name' } = props;