I declare a type and instantiate it in one go.
Now I want to reference a property (y=x+1
) from another like so:
private data:
{
x: number;
y: number;
} = {
x: 1,
y: x + 1, // "Cannot find name 'x'.ts(2304)"
};
Is it even possible?
Update
Please note that the statement contains a declaration and then an instantiation. A suggested answer only instantiates the object.
Reason for discrepancy: The resulting javascript might be the same and the editor of choice might behave similarly; but when a human reads and edits the code there is a difference between the declaration and implementation. The real use case is more complex than the example in this question.
Answer
The question asks for both Declaration and Instantiation which was answered by @AlekseyL. in a comment. The linked answer is copied here:
const data:
{
x: number;
readonly y: number;
} = {
x: 1,
get y() {
return this.x + 1
}
};```