M
M
Mikenzzz2018-06-29 13:29:31
typescript
Mikenzzz, 2018-06-29 13:29:31

How to create an instance of a class that has properties - instances of another class?

Good afternoon!
There are two:

export class TestObject {

  constructor(init?: Partial<TestObject>) {
    Object.assign(this, init);
  }

  id: number;
  name: string;
  well: Well;

}

export class Well {

  constructor(init?: Partial<Well>) {
    Object.assign(this, init);
  }

  id: number;
  name: string;
  x: number;
  y: number;
}
```

С бэкенда приходит объект

```
obj = {
  id: 1,
  name: 'first',
  well: {
    id: 2,
    name: 'second',
    x: 1,
    y: 1
  }
}

Why, when creating an instance of the TestObject class - new TestObject(obj), the value of the well attribute is not an instance of the Well class (the Well constructor is not called).
Should I call it explicitly in the constructor of the TestObject class? Or is it a crutch and you shouldn't do it? How to proceed then?
this.well = new Well(init.well);

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question