5

What I need is fairly simple, I just want to initialize an object that is a child of another object which I am initializing. In C# it would look something like this:

var car = new Car { 
serialNumber = 25,
engine = new Engine {
    horsePower = 500
    }
}

In this example code I am initializing the Engine type inside the initialization of the Car type. While trying to do this with TypeScript no matter what I try I get syntax errors.

Here is my TypeScript code:

var car: Car = new Car({
serialNumber: 25,
    engine: new Engine({ 
        horsePower: 500
    })
});

This block of code just does not work, and all the classes used in the code here are obviously imported.

Could it really be a basic feature like this isn't supported in TypeScript?

EDIT: There is no constructor in these classes. Here's how they look:

export class Car { 
    serialNumber: number;
    engine: Engine;
}
2
  • If that piece of code is giving you errors, I would just suggest to initialize "Engine" before the initialization of Car and then use it on the Car class initialization ;) Commented Mar 1, 2017 at 1:03
  • @gascon95 This code is only for reference, In my code it is far more complicated, I have multiple objects to initialize and I find it time consuming and ineffective to initialize each object beforehand and create a variable. The solution is obviously easy, but the question is if that really is the only way? Commented Mar 1, 2017 at 1:05

2 Answers 2

8

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).

Sign up to request clarification or add additional context in comments.

7 Comments

I added an example code of the class, And i'll try using interface and see what happens.
Ok. I see your class has properties but no constructor. This means you can't instantiate it with properties, either nested or one at a time. Is your question really "how do I initialize a class instance with properties without using a constructor?"
Yeah I guess so, sorry for misleading. Also I found something else that is dumb, if i have a constructor without parameters and initialize the object the constructor code won't fire. The more i use typescript the more I hate it :/
if i have a constructor without parameters and initialize the object the constructor code won't fire -- that's definitely not true, something else must be wrong with your code.
It sounds retarded but I'm telling you, that's how it is. After adding a useless parameter just to verify the constructor code works.
|
0

Your answer is definitely you can. But you syntax has a probelm.

var car = new Car(
       serialNumber: 25,
      engine: new Engine{ 
      horsePower: 500
     }
 ); 

and the Car class should be like this:

public class Car(int serialNumber, Engine engine) {

 .....
}

6 Comments

I'm afraid I'm still getting the same error: Supplied parameters do not match any signature of call target.
As I said, you Car class structure should look like above. What is the Car class structure?
I modified the post, I made a mistake in writing that.
It makes no difference and i don't see how it would've made a difference.
As I said, there is an issue with class constructor. The class could simply have no constructors. Check that. You may copy it here.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.