在TypeScript中扩展与实现纯抽象类 [英] Extending vs. implementing a pure abstract class in TypeScript

查看:132
本文介绍了在TypeScript中扩展与实现纯抽象类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个纯抽象类(即没有任何实现的抽象类):

Suppose I have a pure abstract class (that is, an abstract class without any implementation):

abstract class A {
    abstract m(): void;
}

就像C#和Java一样,我可以扩展抽象类:

Like in C# and Java, I can extend the abstract class:

class B extends A {
    m(): void { }
}

但是不同,在C#和Java中,我也可以实现抽象类:

But unlike in C# and Java, I can also implement the abstract class:

class C implements A {
    m(): void { }
}

B 和<$ c如何做$ c> C 的行为有所不同吗?为什么我要选择一个而不是另一个?

How do classes B and C behave differently? Why would I choose one versus the other?

(当前,TypeScript 手册语言规范涵盖抽象类。)

(Currently, the TypeScript handbook and language specification don't cover abstract classes.)

推荐答案

实现关键字将A类视为接口,这意味着 C必须实施A 中定义的所有方法,无论它们是否在 A 中实现。在 C 中也没有调用超级方法。

The implements keyword treats the A class as an interface, that means C has to implement all the methods defined in A, no matter if they have an implementation or not in A. Also there are no calls to super methods in C.

扩展的行为更像您期望的那样关键字。您只需实现抽象方法,就可以使用/生成超级调用。

extends behaves more like what you'd expect from the keyword. You have to implement only the abstract methods, and super calls are available/generated.

我想在抽象方法的情况下,它没有什么作用。但是您很少有只使用抽象方法的,如果您这样做,最好将其转换为接口

I guess that in the case of abstract methods it does not make a difference. But you rarely have a class with only abstract methods, if you do it would be much better to just transform it to an interface.

通过查看生成的代码,您可以轻松地看到这一点。我做了一个游乐场示例此处

You can easily see this by looking at the generated code. I made a playground example here.

这篇关于在TypeScript中扩展与实现纯抽象类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆