Typescript:从父类获取扩展类的属性

3

在抽象类的方法中,如何获取子类的属性?

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();
2个回答

0

我稍微改进了你的代码,你错过的是缺少super(),这表示子类继承了其父类的所有属性。此外,父类中的属性需要标记为抽象,或者它们需要在父类中实现。

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 关键字并在父类中实现该方法。

编辑

我有另一种实现方式,你可以在父类中定义该方法并简单地记录 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(); 

-1
abstract class Parent {
  constructor(public id?: string) {}
  logProps() {
      console.log(Object.keys(this));
    }
}

class Child extends Parent {    
  constructor(public id?: string, public name?: string) {
    super(id);
  }
}

const child = Child('01', "Daniel");
child.logProps(); 

1
你应该尝试解释一下这个是如何解决原帖提出的问题的。 - guzmonne
这不是正确的答案。 - xTwisteDx

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接