Reputation: 21
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
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
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