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

推荐订阅源

Hugging Face - Blog
Hugging Face - Blog
Google DeepMind News
Google DeepMind News
云风的 BLOG
云风的 BLOG
WordPress大学
WordPress大学
Vercel News
Vercel News
Apple Machine Learning Research
Apple Machine Learning Research
T
Tailwind CSS Blog
I
InfoQ
小众软件
小众软件
Recent Announcements
Recent Announcements
博客园 - 【当耐特】
The GitHub Blog
The GitHub Blog
大猫的无限游戏
大猫的无限游戏
美团技术团队
T
The Blog of Author Tim Ferriss
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
酷 壳 – CoolShell
酷 壳 – CoolShell
MongoDB | Blog
MongoDB | Blog
V
V2EX
J
Java Code Geeks
有赞技术团队
有赞技术团队
博客园 - 聂微东
B
Blog RSS Feed
博客园 - 司徒正美

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.