I have a Foo and a Bar class:
class Foo {
  
  private name: string;
  private bar: Bar;
  constructor(name: string, bar: Bar) {
    this.name = name;
    this.bar = bar;
  }
}
class Bar {
  private x: number;
  private y: number;
  constructor(x: number, y: number) {
    this.x = x;
    this.y = y;
  }
}
Now using the Typescript constructor shorthand I could write Foo as:
class Foo {
  constructor(private name: string, private bar: Bar) { }
}
However what I would like to do, is instead of passing a Bar object into the Foo constructor. Is instead pass in the values of x and y, but still maintain using the shorthand notation to save me writing out the class in full.
Effectively, can this:
class Foo {
  
  private name: string;
  private bar: Bar;
  constructor(name: string, x: number, y: number) {
    this.name = name;
    this.bar = new Bar(x, y);
  }
}
Be written making use of the shorthand notation?
The shorthand notation is called "parameter properties", and specifically just copies a constructor parameter to a same-named class property.  It isn't suitable for what you're doing with bar.  You can still use the shorthand for the name property, like this:
class Foo {
    private bar: Bar;
    constructor(private name: string, x: number, y: number) {
        this.bar = new Bar(x, y);
    }
}
which is how I'd recommend you proceed.
If someone were to threaten me with bodily harm unless I came up with some way to use parameter properties for your bar scenario, I suppose I could abuse default parameters like this:
// ☠ DON'T DO THIS ☠
class AbuseFoo {
    constructor(
        private name: string,
        x: number, y: number,
        private bar: Bar = new Bar(x, y)
    ) { }
}
This "works" in that
// ☠ DON'T DO THIS ☠
let f = new AbuseFoo("name", 1, 2);
console.log(JSON.stringify(f)); // {"name":"name","bar":{"x":1,"y":2}}
produces a value containing a private bar property whose x is 1 and y is 2.  But it exposes an optional fourth constructor parameter that overrides the x and y properties:
f = new AbuseFoo("name", 1, 2, new Bar(3, 4)); 
console.log(JSON.stringify(f)); // {"name":"name","bar":{"x":3,"y":4}}
And of course, it's ugly and more complicated than just declaring bar in the class and setting it in the constructor the normal way.  So unless you have some very good reason to do this (e.g., code obfuscation contest, threats of bodily harm, etc), I'd stick with the original answer:
No, you can't use parameter properties to set bar that way.  Use the longhand method.
Playground link to code
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With