abstract 用於定義抽象類和其中的抽象方法。app
什麼是抽象類?this
首先,抽象類是不容許被實例化的:spa
abstract class Animal { public name; public constructor(name) { this.name = name; } public abstract sayHi(); } let a = new Animal('Jack'); // index.ts(9,11): error TS2511: Cannot create an instance of the abstract class 'Animal'.
上面的例子中,咱們定義了一個抽象類 Animal,而且定義了一個抽象方法 sayHi。在實例化抽象類的時候報錯了。prototype
其次,抽象類中的抽象方法必須被子類實現:code
abstract class Animal { public name; public constructor(name) { this.name = name; } public abstract sayHi(); } class Cat extends Animal { public eat() { console.log(`${this.name} is eating.`); } } let cat = new Cat('Tom'); // index.ts(9,7): error TS2515: Non-abstract class 'Cat' does not implement inherited abstract member 'sayHi' from class 'Animal'.
上面的例子中,咱們定義了一個類 Cat 繼承了抽象類 Animal,可是沒有實現抽象方法 sayHi,因此編譯報錯了。blog
下面是一個正確使用抽象類的例子:繼承
abstract class Animal { public name; public constructor(name) { this.name = name; } public abstract sayHi(); } class Cat extends Animal { public sayHi() { console.log(`Meow, My name is ${this.name}`); } } let cat = new Cat('Tom');
上面的例子中,咱們實現了抽象方法 sayHi,編譯經過了。ip
須要注意的是,即便是抽象方法,TypeScript 的編譯結果中,仍然會存在這個類,上面的代碼的編譯結果是:it
var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Animal = (function () { function Animal(name) { this.name = name; } return Animal; }()); var Cat = (function (_super) { __extends(Cat, _super); function Cat() { _super.apply(this, arguments); } Cat.prototype.sayHi = function () { console.log('Meow, My name is ' + this.name); }; return Cat; }(Animal)); var cat = new Cat('Tom');