Typescript-调用super的子类函数返回父类类型

时间:2019-01-16 16:04:28

标签: typescript inheritance

我对打字稿中的继承方案感到困惑。调用super时,我似乎无法返回子类型。有人可以解释为什么此示例不返回子类型吗? as的作用是什么?有没有办法实现这种行为?

class Parent {
    _value: number
    constructor(value: number){
        this._value = value
    }
    add(x: Parent): Parent {
        return new Parent(x._value + this._value)
    }
}

class Child extends Parent {
    constructor(value: number) {
        super(value)
    }
    add(x: Child): Child {
        return super.add(x) as Child
    }
}

let a = new Child(10)
let b = new Child(5)
let c = a.add(b)

console.log(a)
console.log(b)
console.log(c)

输出:

Child { _value: 10 }
Child { _value: 5 }
Parent { _value: 15 }

1 个答案:

答案 0 :(得分:0)

对于这种多态性,应该使用“ new this.constructor()”。并为TypeScript返回类型为“ this”的类型。此后,您无需覆盖该方法。

相关问题