元素码农
基础
UML建模
数据结构
算法
设计模式
网络
TCP/IP协议
HTTPS安全机制
WebSocket实时通信
数据库
sqlite
postgresql
clickhouse
后端
rust
go
java
php
mysql
redis
mongodb
etcd
nats
zincsearch
前端
浏览器
javascript
typescript
vue3
react
游戏
unity
unreal
C++
C#
Lua
App
android
ios
flutter
react-native
安全
Web安全
测试
软件测试
自动化测试 - Playwright
人工智能
Python
langChain
langGraph
运维
linux
docker
工具
git
svn
🌞
🌙
目录
▶
TypeScript环境准备
安装与配置
第一个TS程序
编译流程解析
▶
基础类型系统
类型注解语法
原始类型定义
数组与元组
接口与对象
▶
高级类型系统
泛型编程
条件类型
映射类型
类型推断
类型保护
高级类型工具
▶
函数开发
函数类型声明
可选参数与默认值
箭头函数应用
函数重载
泛型函数
▶
类与面向对象
类的定义
继承与修饰符
存取器使用
抽象类与接口
泛型类与抽象类
访问修饰符与属性
▶
模块化开发
模块导入导出
类型声明文件
命名空间
模块解析策略
▶
工程实践
tsconfig详解
常见编译选项
项目构建配置
代码组织最佳实践
单元测试
调试技巧
▶
常见问题
类型错误处理
类型断言技巧
类型兼容性
版本迁移指南
发布时间:
2025-03-31 09:25
↑
☰
# 继承与多态 TypeScript中的继承和多态是面向对象编程的重要概念。本文将详细介绍如何使用这些特性来创建灵活和可扩展的代码。 ## 类的继承 ### 基本继承 ```typescript // 基类 class Animal { constructor(protected name: string) {} move(distance: number = 0): void { console.log(`${this.name} moved ${distance}m.`); } } // 派生类 class Dog extends Animal { constructor(name: string) { super(name); // 调用基类构造函数 } bark(): void { console.log('Woof! Woof!'); } // 重写基类方法 move(distance: number = 5): void { console.log('Running...'); super.move(distance); // 调用基类方法 } } const dog = new Dog('Rex'); dog.bark(); // 'Woof! Woof!' dog.move(); // 'Running...' 然后 'Rex moved 5m.' ``` ## 方法重写 ```typescript class Shape { constructor(protected color: string) {} getArea(): number { return 0; } getInfo(): string { return `This is a ${this.color} shape`; } } class Circle extends Shape { constructor( color: string, private radius: number ) { super(color); } // 重写getArea方法 getArea(): number { return Math.PI * this.radius * this.radius; } // 重写并扩展getInfo方法 getInfo(): string { return `${super.getInfo()} with radius ${this.radius}`; } } ``` ## 抽象类和方法 ```typescript // 抽象基类 abstract class Vehicle { constructor( protected manufacturer: string, protected model: string ) {} // 抽象方法 abstract start(): void; abstract stop(): void; // 具体方法 getInfo(): string { return `${this.manufacturer} ${this.model}`; } } // 具体类 class Car extends Vehicle { start(): void { console.log('Starting the car...'); } stop(): void { console.log('Stopping the car...'); } } class Motorcycle extends Vehicle { start(): void { console.log('Starting the motorcycle...'); } stop(): void { console.log('Stopping the motorcycle...'); } } ``` ## 多态 ```typescript // 基类和接口 abstract class Animal { constructor(protected name: string) {} abstract makeSound(): void; } interface Pet { play(): void; } // 实现多态 class Cat extends Animal implements Pet { makeSound(): void { console.log('Meow!'); } play(): void { console.log(`${this.name} is playing with a ball of yarn.`); } } class Dog extends Animal implements Pet { makeSound(): void { console.log('Woof!'); } play(): void { console.log(`${this.name} is playing fetch.`); } } // 多态使用 function playWithPet(pet: Pet): void { pet.play(); } const cat = new Cat('Whiskers'); const dog = new Dog('Rex'); playWithPet(cat); // "Whiskers is playing with a ball of yarn." playWithPet(dog); // "Rex is playing fetch." ``` ## 接口继承 ```typescript interface Shape { getArea(): number; } interface Color { getColor(): string; } // 接口继承 interface ColoredShape extends Shape, Color { getBorder(): string; } // 实现多重接口 class Square implements ColoredShape { constructor( private side: number, private color: string, private borderStyle: string ) {} getArea(): number { return this.side * this.side; } getColor(): string { return this.color; } getBorder(): string { return this.borderStyle; } } ``` ## 最佳实践 1. **使用抽象类定义契约**: ```typescript abstract class DataSource { abstract connect(): void; abstract disconnect(): void; abstract fetch(id: string): Promise<any>; // 共享功能 isConnected(): boolean { // 实现连接检查逻辑 return true; } } class MySQLDataSource extends DataSource { connect(): void { // 实现MySQL连接 } disconnect(): void { // 实现MySQL断开连接 } fetch(id: string): Promise<any> { // 实现MySQL数据获取 return Promise.resolve(); } } ``` 2. **合理使用protected**: ```typescript class Base { protected sharedMethod(): void { // 可以被子类访问的方法 } private restrictedMethod(): void { // 仅基类可以访问的方法 } } ``` 3. **使用组合而非继承**: ```typescript // 优先使用组合 class Engine { start(): void {} stop(): void {} } class Car { constructor(private engine: Engine) {} start(): void { this.engine.start(); } } ``` ## 常见问题 1. **构造函数继承**: ```typescript class Parent { constructor(protected name: string) {} } class Child extends Parent { constructor(name: string, private age: number) { super(name); // 必须先调用super() // 然后才能使用this console.log(this.age); } } ``` 2. **多重继承限制**: ```typescript // TypeScript不支持多重继承 // 使用接口来模拟多重继承 interface A { methodA(): void; } interface B { methodB(): void; } class C implements A, B { methodA(): void {} methodB(): void {} } ``` ## 下一步 掌握了继承和多态后,你可以: 1. 学习更多设计模式 2. 探索泛型类的使用 3. 实践面向对象的SOLID原则 4. 了解装饰器模式 通过合理使用继承和多态,你可以创建更加灵活和可维护的面向对象代码。