Pete
Pete

Reputation: 3451

How to safely destructure a JavaScript object in TypeScript

I want to pull out attributes from a JavaScript object (below) but want to protect myself from either the object being null or undefined as well as the properties not existing. That is, I want the values to just be undefined and not have the JavaScript error.

const {id,username,userFirstName,userLastName} = attendeeResults;

Upvotes: 5

Views: 5098

Answers (5)

Dayoolacodes
Dayoolacodes

Reputation: 56

building on the response by José Salgado. Ensure to use ?? Nullish Coalescing Operator since you are actually checking for null

const { foo, bar } = null ?? {};

console.log(foo, bar);

Upvotes: 0

José Salgado
José Salgado

Reputation: 1072

You can use logical operators to achieve that:

const nullObject = null;
const { foo, bar } = nullObject || {};

console.log(foo, bar);

Upvotes: 7

tolotra
tolotra

Reputation: 3270

JavaScript allow you to define default value when destructuring an object. For example:

const {id: 0,username:'',userFirstName:'',userLastName:''} = attendeeResults;

But destruncturing throws an error if your attendeeResults object is null or undefined.

Upvotes: 2

behzad besharati
behzad besharati

Reputation: 6910

This can be done this way:

const {id, username, ...rest} = {id: 10, username: 'u', firstname:'behzad',lastname:'besharati'};


console.log(id,username,rest);

Upvotes: 0

Rafael Herscovici
Rafael Herscovici

Reputation: 17094

You could use the following, Please notice that i omitted username in the attendee to show that it keeps the null value.

const attendeeResults = { id: 1, userFirstName: 'John', userLastName: 'Smith'}
const obj = {
  id: null,
  username: null,
  userFirstName: null,
  userLastName: null
};
Object.assign(obj, attendeeResults);
console.log(obj);

Upvotes: -1

Related Questions