抽象类与 this 类型
约 239 字小于 1 分钟
布欧-Lewyon
2026-05-16
首页 › TypeScript › 类与面向对象 › 抽象类与 this 类型
抽象类
abstract class Animal {
constructor(public name: string) {}
// 具体方法
move(): void {
console.log(`${this.name} 在移动`);
}
// 抽象方法(子类必须实现)
abstract makeSound(): void;
}
class Dog extends Animal {
makeSound(): void {
console.log('汪汪!');
}
}
// const a = new Animal('动物'); // ❌ 不能实例化抽象类
const dog = new Dog('狗');
dog.makeSound(); // "汪汪!"implements
interface Flyable {
fly(): void;
}
interface Swimmable {
swim(): void;
}
class Duck implements Flyable, Swimmable {
fly() { console.log('飞'); }
swim() { console.log('游'); }
}this 类型(链式调用)
class Calculator {
constructor(public value = 0) {}
add(n: number): this {
this.value += n;
return this;
}
multiply(n: number): this {
this.value *= n;
return this;
}
getResult(): number {
return this.value;
}
}
const result = new Calculator(1)
.add(5) // 6
.multiply(3) // 18
.getResult(); // 18小结
| 概念 | 说明 |
|---|---|
abstract class | 不可实例化,提供抽象方法定义 |
implements | 类实现接口 |
this 返回类型 | 支持链式调用 |
上一节:类与修饰符 下一节:装饰器(TS 5.0+)
