Typescript: получить свойства расширяющего класса из родительского класса. - PullRequest
1 голос
/ 20 марта 2019

Как я могу получить свойства дочернего класса в методе абстрактного класса?

abstract class Parent {

    id: string;

    logProps() {
        // HOW can I log all properties of a child class
        // and their values? For example, the name.
    }
}

class Child extends Parent {

    name: string;

    constructor(name) {
        super();
        this.name = name;
    }
}

const child = new Child("Daniel");
child.logProps(); 

1 Ответ

0 голосов
/ 20 марта 2019

Я немного улучшил ваш код, но вы упустили отсутствие super(), это говорит о том, что дочерний класс наследует все свойства от своего родительского класса. Также атрибуты в классе parrent должны быть помечены как абстрактные, или они должны быть реализованы в классе parrent.

abstract class Parent {
abstract id: string;

 abstract logProps(): Parent; // make abstract or implement here
}

class Child extends Parent {
    id: string;
    name: string;

    constructor(name: string) {
       super();
       this.id = ""//some initial value
       this.name = name;
  }

    logProps(): Parent {
       return this;
    }
} 

const child = new Child("Daniel");
child.logProps();

Я решил сделать все свойства абстрактными, вы также можете удалить ключевое слово abstract и реализовать метод в родительском классе.

EDIT

У меня есть другая реализация, вы можете определить метод в классе parrent и просто записать в журнал this, он будет содержать все свойства.

abstract class Parent {

id: string = "DEFAULT VALUE";

logProps() {
    console.log(this); // Using this, this contains all properties
 }
}

class Child extends Parent {

name: string;

constructor(name: string) {
    super();
    this.name = name;
 }
}

const child = new Child("Daniel");
child.logProps(); 
...