3

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';
Nikolai
  • 555
  • 7
  • 17

2 Answers2

4

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

const { id, name = 'placeholder name' } = props;
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • I didn't know that, but it works. Thanks for the answer. I will accept the answer in 10 minutes – Nikolai Jan 21 '21 at 17:57
0

To solve this possible problem i do it

Example:

const defaultValue = 'It's a Empty Value';

let {name, age, lastName} = person;

$('#div_Teste').append(`<p>Name: ${name ?? defaultValue}, Age ${age ?? defaultValue }, Last name: ${lastName ?? defaultValue}</p>`

I have put nullish on the moment to use the variables.