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

查看:34
本文介绍了在 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 { }
}

BC 类的行为有何不同?为什么我会选择一个而不是另一个?

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.)

推荐答案

implements 关键字将 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 的行为更像您对关键字的期望.您只需实现抽象方法,并且可以使用/生成超级调用.

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天全站免登陆