You can certainly do this, you just have to pass the correct constructor arguments.
The code you've written passes a single constructor argument object with keys. So your classes should look something like this:
class Car {
constructor(args: { serialNumber: number; engine: Engine; }) { }
}
class Engine {
constructor(args: { horsePower: number; }) { }
}
If, however, your classes use multiple named constructor arguments, like this:
class Car {
constructor(serialNumber: number, engine: Engine) { }
}
class Engine {
constructor(horsePower: number) { }
}
Then you simply have to pass your constructor arguments correctly:
const car: Car = new Car(25, new Engine(500));
EDIT
that would require me to create a constructor which is kind of annoying
I'm a bit confused... your original code uses classes, so you should already have a constructor unless you are adding each property using an assignment. Please post a complete example.
If you're just trying to create a nested object literal structure, you just need an interface, then create the object using normal JS object literal notation:
interface Car {
serialNumber: number;
engine: Engine;
}
interface Engine {
horsePower: number;
}
const car: Car = {
serialNumber: 25,
engine: {
horsePower: 500
}
};
If you're trying to assign an object literal to a class type, then you're doing it wrong. :)
EDIT 2
So, you have a class with properties and no constructor. This means you can't instantiate it with properties, either nested or one at a time. You could write a generic helper function to instantiate a class and assign properties:
function create<T>(constructor: new() => T, props: Partial<T>): T {
let instance = new constructor();
for (let key in props) {
instance[key] = props[key];
}
return instance;
}
And then create a nested class object like this:
const car = create(Car, {
serialNumber: 123,
engine: create(Engine, {
horsePower: 456
})
});
But if your classes really just have properties, I think you'd be better off just using interfaces and object literals (as in my previous example).