元素码农
基础
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:27
↑
☰
# 泛型类与抽象类 TypeScript中的泛型类和抽象类是两个强大的面向对象编程特性。本文将详细介绍如何使用这些特性来创建灵活和可重用的代码。 ## 泛型类 ### 基本泛型类 ```typescript // 基本泛型类定义 class Container<T> { private value: T; constructor(value: T) { this.value = value; } getValue(): T { return this.value; } setValue(value: T): void { this.value = value; } } // 使用泛型类 const numberContainer = new Container<number>(42); const stringContainer = new Container<string>("Hello"); console.log(numberContainer.getValue()); // 42 console.log(stringContainer.getValue()); // "Hello" ``` ### 多类型参数 ```typescript class KeyValuePair<K, V> { constructor( private key: K, private value: V ) {} getKey(): K { return this.key; } getValue(): V { return this.value; } } const pair = new KeyValuePair<string, number>("age", 25); console.log(pair.getKey()); // "age" console.log(pair.getValue()); // 25 ``` ### 泛型约束 ```typescript // 定义接口作为约束 interface Lengthwise { length: number; } class Collection<T extends Lengthwise> { constructor(private items: T[]) {} getItemLength(index: number): number { return this.items[index].length; } } // 使用约束泛型类 const stringCollection = new Collection<string>(["hello", "world"]); const arrayCollection = new Collection<number[]>([[1, 2], [3, 4]]); ``` ## 抽象类 ### 基本抽象类 ```typescript // 定义抽象类 abstract class Animal { constructor(protected name: string) {} // 抽象方法 abstract makeSound(): void; // 具体方法 move(distance: number = 0): void { console.log(`${this.name} moved ${distance}m.`); } } // 实现抽象类 class Dog extends Animal { makeSound(): void { console.log('Woof! Woof!'); } } class Cat extends Animal { makeSound(): void { console.log('Meow!'); } } ``` ### 抽象属性 ```typescript abstract class Shape { // 抽象属性 abstract color: string; // 抽象获取器 abstract get area(): number; // 具体方法 getInfo(): string { return `This is a ${this.color} shape with area ${this.area}`; } } class Circle extends Shape { color: string; private radius: number; constructor(color: string, radius: number) { super(); this.color = color; this.radius = radius; } get area(): number { return Math.PI * this.radius * this.radius; } } ``` ## 结合泛型和抽象类 ```typescript // 泛型抽象类 abstract class DataStorage<T> { protected data: T[] = []; abstract add(item: T): void; abstract remove(item: T): void; getItems(): T[] { return [...this.data]; } } class ArrayStorage<T> extends DataStorage<T> { add(item: T): void { this.data.push(item); } remove(item: T): void { const index = this.data.indexOf(item); if (index !== -1) { this.data.splice(index, 1); } } } // 使用示例 const storage = new ArrayStorage<string>(); storage.add("TypeScript"); storage.add("JavaScript"); console.log(storage.getItems()); // ["TypeScript", "JavaScript"] ``` ## 最佳实践 1. **使用泛型约束**: ```typescript interface HasId { id: number; } class Repository<T extends HasId> { private items: T[] = []; save(item: T): void { const index = this.items.findIndex(i => i.id === item.id); if (index === -1) { this.items.push(item); } else { this.items[index] = item; } } } ``` 2. **抽象工厂模式**: ```typescript abstract class UIFactory { abstract createButton(): Button; abstract createInput(): Input; // 共享逻辑 createForm(): Form { const button = this.createButton(); const input = this.createInput(); return new Form(button, input); } } ``` 3. **泛型方法**: ```typescript class Utilities { static map<T, U>(array: T[], fn: (item: T) => U): U[] { return array.map(fn); } static filter<T>(array: T[], fn: (item: T) => boolean): T[] { return array.filter(fn); } } ``` ## 常见问题 1. **泛型类型推断**: ```typescript class Box<T> { value: T; constructor(value: T) { this.value = value; } } // 类型推断 const box = new Box("hello"); // Box<string> const numberBox = new Box<number>(42); // 显式类型 ``` 2. **抽象类vs接口**: ```typescript // 抽象类可以包含实现 abstract class Base { abstract method(): void; helper(): void { console.log("Helper method"); } } // 接口只能声明结构 interface IBase { method(): void; } ``` ## 下一步 掌握了泛型类和抽象类后,你可以: 1. 学习更多设计模式 2. 探索装饰器的使用 3. 实践依赖注入 4. 了解高级类型系统 通过合理使用泛型类和抽象类,你可以创建更加灵活和可重用的面向对象代码。