-1

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
  }
};```
LosManos
  • 7,195
  • 6
  • 56
  • 107

1 Answers1

0

Is this what you want?

Creating a function that return your desired value. In this case x+1.

var data = function(){
    var x = 1;
    var y = x +1;
    return{
      x: x,
      y: y
    }
    
  }();
console.log(data)

This is a JS example but here is a TS playground which need similar code:

var data:
  {
    x: number;
    y: number;
  } = function(){
    var x = 1;
    var y = x +1;
    return{
      x: x,
      y: y
    }
    
  }();

JS and TS output is the same, the object with desired properties values:

{
  "x": 1,
  "y": 2
}
J.F.
  • 13,927
  • 9
  • 27
  • 65
  • Not really a solution the question. I want to differ clearly between the declaration and instantation due to reasons outside this question. – LosManos Jan 07 '21 at 12:26
  • 1
    @LosManos If the reason affects which answers are acceptable - then it cannot reasonably be outside this question. The people writing answers need to know in order to give proper answers without doing wild guesses and not waste their own or your time. – fredrik Jan 07 '21 at 12:31
  • @fredrik What I mean is that there are lots of solution that makes it possible to have a data structure with properties and functions. But the very syntax I am proposing is due to present architect, present developers and other soft values. – LosManos Jan 07 '21 at 12:38