2

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)

user3372174
  • 21
  • 1
  • 3
  • Not sure that either of those will work at all. I don't think you can reference an object in it's own initializer, with either `var` or `const`. It's unfortunate that typescript doesn't complain about the first case, since both of these will produce runtime error: `cannot read property 'x' of undefined` – CRice Dec 08 '17 at 21:24
  • In the first case it does not complain (I'm in Visual Code) – user3372174 Dec 08 '17 at 21:42

2 Answers2

1

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);
Christian Santos
  • 5,386
  • 1
  • 18
  • 24
  • The first code (var v...) does NOT throw an error, I've tested it in Visual Code. See first answer in https://stackoverflow.com/questions/4892221/i-need-to-call-a-parent-property-from-child-object-in-an-object-literal What you propose for c is just what I proposed like a solution. Thanks anyway ;) – user3372174 Dec 08 '17 at 21:40
1

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());
Dave Cousineau
  • 12,154
  • 8
  • 64
  • 80