



























An abstract is a class with unimplemented methods.
It can’t be instantiated and but an other class can extend it to reuse it’s functionality.
abstract class Shape {
constructor(protected name: string) { }
public printName() {
console.log(`I am a ${this.name}`);
}
abstract printPerimeter(): void;
}
class Square extends Shape {
private side: number;
constructor(side: number) {
super('Square');
this.side = side;
}
printPerimeter() {
console.log(`${this.name} has a perimeter of ${this.side * 4}`);
}
}
const square = new Square(10);
square.printName();
square.printPerimeter();
Abstract classes in TypeScript require TypeScript 1.6 or above.
name is protected so it can only be accessed in the base class and the classes inherited from it.
constructor(protected name: string)
is a shorter way of writing
protected name: string;
constructor(name: string) {
this.name = name;
}
Abstract classes produce a JavaScript class as they get transpiled.
The abstract class above results in
class Shape {
constructor(name) {
this.name = name;
}
printName() {
console.log(`I am a ${this.name}`);
}
}
Interfaces have all their members public and abtract.
They do not produce any JavaScript code -> They are only used in TypeScript.
If your abstract class only has abstract and public members, you could consider using an interface instead.
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。