惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

人人都是产品经理
人人都是产品经理
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
月光博客
月光博客
雷峰网
雷峰网
Google DeepMind News
Google DeepMind News
Y
Y Combinator Blog
Microsoft Security Blog
Microsoft Security Blog
M
MIT News - Artificial intelligence
WordPress大学
WordPress大学
MongoDB | Blog
MongoDB | Blog
V
V2EX
博客园 - 【当耐特】
GbyAI
GbyAI
Stack Overflow Blog
Stack Overflow Blog
I
InfoQ
Martin Fowler
Martin Fowler
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Hugging Face - Blog
Hugging Face - Blog
B
Blog
V
Visual Studio Blog
D
DataBreaches.Net
C
Check Point Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
F
Fortinet All Blogs

CodeBlocQ

Jest - Mock Local Storage Have Mobx and React work with TypeScript Loose assertions on arguments passed to function with Jest Check if a Docker image exists locally A-Star Pathfinding React Demo My Free and Open Source Expense Tracker App is on the App Store Pass artifacts around in between stages in gitlab CI How to start a tech company as a non technical individual Setup gitment on your Hexo blog
TypeScript Abstract Class
Jonathan Klughertz · 2020-07-17 · via CodeBlocQ

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.

TypeScript Abstract Class Example

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();

Notes

Available in TypeScript 1.6

Abstract classes in TypeScript require TypeScript 1.6 or above.

The protected keyword

name is protected so it can only be accessed in the base class and the classes inherited from it.

Constructor Shorthand

constructor(protected name: string) 

is a shorter way of writing

protected name: string;

constructor(name: string) {
this.name = name;
}

Code Output

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}`);
}
}

Difference with interfaces

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.