skip to Main Content

I have two Typescript objects x and y as defined below:

let x = {A: 1, B: 2};
console.log('x = ', x);
let y = {A: 1};
console.log('y = ', y);

> x = {"A": 1, "B": 2} 
> y = {"A": 1} 

Now I want to set y.B to x.B iff x.B exists.
And I want to set y.C to x.C iff x.C exists.

Is there an operator I can use to achieve this? Currently I do this, but it seems clunky:

if (x.hasOwnProperty('B') && x.B !== null) {
    y.B = x.B;
}
if (x.hasOwnProperty('C') && x.C !== null) {
    y.C = x.C;
}

2

Answers


  1. Not exactly sure about what you want to do but maybe this is the case for the Optional Chaining operator (?.).

    It can be used like this:

    if (x?.B !== null) {
        y.B = x.B;
    }
    if (x?.C !== null) {
        y.C = x.C;
    }
    

    This operator checks for the existence of that property before accessing it. It accesses the x.C and evaluates the expression to undefined if it throws an error (instead of throwing the error).

    Login or Signup to reply.
  2. In most cases your code is equivalent of

    y.B = x.B ?? y.B;
    y.C = x.C ?? y.C;
    

    (except if x prototype has B or if x.B is undefined)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search