【问题标题】:Typescript: Access properties of Sub class from Base class setter打字稿:从基类设置器访问子类的属性
【发布时间】:2020-01-31 06:07:59
【问题描述】:

我有一个子类 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]
            }
        }
    }
}

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

提前致谢。

【问题讨论】:

  • JavaScript 允许各种疯狂的事情,因为它是动态的,但是从基类访问子类会完全破坏 OO

标签: node.js typescript inheritance


【解决方案1】:

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

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

Playground

【讨论】:

  • 在第 12 行 this[f] = props[f] 有一个错误元素隐式具有“任何”类型,因为“字符串”类型的表达式不能用于索引“人”类型.在“Person”类型上找不到带有“字符串”类型参数的索引签名。你也如何解决这个问题?
  • @Sarita 您可以尝试定义类型保护,但在这种特定情况下,我只会// @ts-ignore 错误
猜你喜欢
  • 2018-09-06
  • 2017-08-03
  • 2015-10-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-11
  • 2021-03-21
  • 1970-01-01
相关资源
最近更新 更多