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

832 views Asked by At

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';
2

There are 2 answers

1
CertainPerformance On BEST ANSWER

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

const { id, name = 'placeholder name' } = props;
0
CodeHatGuerra On

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.