user3372174
user3372174

Reputation: 21

Typescript: Accessing a parent property from child object in a constant

In this Typescript/Javascript code:

var v= {
  x: 1,
  y: {
    z: v.x,
  }
}

const c = {
  x: 1,
  y: {
    z: c.x,
  }
}

v is ok because var is JavaScript and it doesn't complain, but when assigning z in c there is an error because of the use of z before its declaration.

My question: is there a way to get it? (I know I could declare another x out of c and assign its value inside, but I mean something more direct)

Upvotes: 2

Views: 2800

Answers (2)

Dave Cousineau
Dave Cousineau

Reputation: 13168

One possibility is to make z lazy:

var v = {
   x: 1,
   y: {
      z: () => v.x,
   }
}

const c = {
   x: 1,
   y: {
      z: () => c.x,
   }
}

console.log(v.y.z());
console.log(c.y.z());

Upvotes: 1

Christian Santos
Christian Santos

Reputation: 5456

Both examples will throw an error as v does not yet exist at the time when the expression v.x is evaluated:

var

var v= {
  x: 1,
  y: {
    z: v.x, // TypeError
  }
}

const

const c = {
  x: 1,
  y: {
    z: c.x, // TypeError
  }
}

You'll have to resort to adding the object after c is initialized:

const c = {
  x: 1
}

c.y = { z: c.x };

console.log(c.y.z);

Upvotes: 1

Related Questions