【问题标题】:Typescript - Sub class function that calls super returns parent class typeTypescript - 调用 super 的子类函数返回父类类型
【发布时间】:2019-01-16 16:04:27
【问题描述】:

我对打字稿中的继承方案感到困惑。调用 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 }

【问题讨论】:

  • as 关键字只是为了让编译器理解 所谓的 类型。它不会从 A 转变为 B。
  • 在 TS 中,as<> 首先不应该被称为“铸造”(正如您试图做的那样),而是“类型断言者”。这些在运行时中不存在,只是您向编译器提供有关您希望如何分析代码的提示的一种方式。

标签: typescript inheritance


【解决方案1】:

对于这种多态性,您应该使用“new this.constructor()”。对于 TypeScript,返回类型为“this”。在此之后,您不需要重写该方法。

【讨论】:

    猜你喜欢
    • 2014-08-27
    • 2021-07-28
    • 2019-09-03
    • 1970-01-01
    • 2021-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多