【问题标题】:What is the difference between an abstract class and typescript interface? [duplicate]抽象类和打字稿接口有什么区别? [复制]
【发布时间】:2019-10-17 08:28:50
【问题描述】:

我是编程新手。又看不懂抽象类和打字稿接口的区别?

【问题讨论】:

  • 一般而言,读者希望问题作者在此处提问之前先搜索网站。

标签: typescript


【解决方案1】:

主要区别之一是界面只是用来告诉您数据的“形状”。接口根本不生成 JavaScript 代码。见the code vs. the generated JS code here

一个抽象类定义为:

抽象类是可以派生其他类的基类。它们可能不会被直接实例化。与接口不同,抽象类可能包含其成员的实现细节。 abstract 关键字用于定义抽象类以及抽象类中的抽象方法。

通过:https://www.typescriptlang.org/docs/handbook/classes.html

使用常规类,您可以像这样创建它的 new 实例

class MyClass {
    constructor() {}
}

var a = new MyClass();

这意味着你不能new 一个抽象类,你会得到一个错误

abstract class MyAbstractClass {
    constructor() {}
}

var a = new MyAbstractClass();  //error! "Cannot create an instance of an abstract class.
"

抽象类旨在用作“基类”,如下所示:

abstract class Animal {
    constructor(public legs: number, public sound: string) {
        console.log(`I have ${this.legs} legs and I say "${this.sound}"!`)
    }
}

class Dog extends Animal {
    constructor() {
        super(4, 'bark');
    }
}

class Cat extends Animal {
    constructor() {
        super(4, 'meow');
    }
}

var a = new Dog();//Logs: I have 4 legs and I say "bark"!
var b = new Cat();//Logs: I have 4 legs and I say "meow"!

【讨论】:

    【解决方案2】:

    运行时可用的抽象类和编译时可用的接口。例如,我们不能将 instanceof 与接口一起使用。

    let u: any;
    var IsExpressionValid = x instanceof IUser; //This will give error.
    var IsExpressionValid = x instanceof User; //This will not.
    

    【讨论】:

      猜你喜欢
      • 2010-11-13
      • 2013-02-17
      • 2010-12-27
      • 2012-04-28
      • 2019-12-14
      • 2012-07-19
      • 2011-04-04
      相关资源
      最近更新 更多