打字稿:从基类设置器访问子类的属性

时间:2020-01-31 06:07:59

标签: node.js typescript inheritance

我有一个子类Employee和一个基类Person。 在Person类的构造函数中,我调用setter函数,该函数在进行一些验证后设置属性。 但是在setter函数中,我无法获取Employee Class的属性。

//Employee.ts
import Person from "./Person"
class Employee extends Person {
    empID: string = '';
    designation: string = '';

    constructor (props) {
        super(props);
    }
}

let obj = {empID:123,designation:"developer",firstName:"John",lastName:"Doe"}
let employee: Employee = new Employee(obj)

//Person.ts
export default class Person {
    firstName: string = '';

    lastName: string = '';

    constructor (props:object) {
        this.props = props
    }

    set props(props:object) {
        console.log("this",this)
        /***************prints Employee { firstName: '', lastName: '' } cannot access empID and designation  **********/
        for (const f in props) {
            if (this.hasOwnProperty(f)) {
                this[f] = props[f]
            }
        }
    }
}

但这可行

//Employee.ts
import Person from "./Person"
class Employee extends Person {
    empID: string = '';
    designation: string = '';

    constructor () {
        super();
    }
}

let obj = {empID:123,designation:"developer",firstName:"John",lastName:"Doe"}
let employee: Employee = new Employee()
employee.props = obj

//Person.ts
export default class Person {
    firstName: string = '';

    lastName: string = '';

    constructor () {

    }

    set props(props:object) {
        console.log("this",this)
        /***************prints Employee { firstName: '', lastName: '', empID: '', designation: '' }  **********/
        for (const f in props) {
            if (this.hasOwnProperty(f)) {
                this[f] = props[f]
            }
        }
    }
}

在第一个示例中我做错什么了吗

谢谢。

1 个答案:

答案 0 :(得分:1)

调用super时,子类尚未初始化。您可以在props通话之后立即设置super

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

Playground