元素码农
基础
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:23
↑
☰
# 类的定义 TypeScript中的类(Class)是一种面向对象编程的基本构建块。本文将详细介绍如何定义和使用TypeScript类。 ## 基本类定义 ### 类的声明 ```typescript // 基本类定义 class Person { // 属性声明 name: string; age: number; // 构造函数 constructor(name: string, age: number) { this.name = name; this.age = age; } // 方法 sayHello(): void { console.log(`Hello, my name is ${this.name}`); } } // 创建实例 const person = new Person("TypeScript", 25); person.sayHello(); // "Hello, my name is TypeScript" ``` ### 类属性 ```typescript class Student { // 实例属性 name: string; // 静态属性 static schoolName: string = "TypeScript School"; // 只读属性 readonly id: number; // 可选属性 nickname?: string; constructor(name: string, id: number) { this.name = name; this.id = id; } } console.log(Student.schoolName); // 访问静态属性 const student = new Student("John", 1); // student.id = 2; // 错误:只读属性不能修改 ``` ## 访问修饰符 ```typescript class Animal { // 公共属性 public name: string; // 私有属性 private age: number; // 受保护属性 protected type: string; constructor(name: string, age: number, type: string) { this.name = name; this.age = age; this.type = type; } // 公共方法 public makeSound(): void { console.log("Some sound"); } // 私有方法 private getAge(): number { return this.age; } // 受保护方法 protected getType(): string { return this.type; } } ``` ## 参数属性 ```typescript class Point { // 使用参数属性简化代码 constructor( public x: number, public y: number, private z: number = 0 ) {} getPosition(): string { return `(${this.x}, ${this.y}, ${this.z})`; } } const point = new Point(1, 2); console.log(point.getPosition()); // "(1, 2, 0)" ``` ## 存取器 ```typescript class Employee { private _salary: number; constructor(private name: string, salary: number) { this._salary = salary; } // 获取器 get salary(): number { return this._salary; } // 设置器 set salary(value: number) { if (value >= 0) { this._salary = value; } } } const employee = new Employee("John", 50000); console.log(employee.salary); // 使用获取器 employee.salary = 60000; // 使用设置器 ``` ## 抽象类 ```typescript // 抽象类定义 abstract class Shape { constructor(protected color: string) {} // 抽象方法 abstract calculateArea(): number; // 具体方法 displayColor(): void { console.log(`This shape is ${this.color}`); } } // 实现抽象类 class Circle extends Shape { constructor(color: string, private radius: number) { super(color); } calculateArea(): number { return Math.PI * this.radius * this.radius; } } ``` ## 实现接口 ```typescript // 定义接口 interface Movable { move(): void; getPosition(): { x: number; y: number }; } interface Resizable { resize(factor: number): void; } // 类实现多个接口 class Rectangle implements Movable, Resizable { constructor( private x: number, private y: number, private width: number, private height: number ) {} move(): void { this.x++; this.y++; } getPosition() { return { x: this.x, y: this.y }; } resize(factor: number): void { this.width *= factor; this.height *= factor; } } ``` ## 最佳实践 1. **使用访问修饰符**: ```typescript class BankAccount { private balance: number; constructor(initialBalance: number) { this.balance = initialBalance; } public deposit(amount: number): void { if (amount > 0) { this.balance += amount; } } } ``` 2. **使用参数属性简化代码**: ```typescript // 好的实践 class User { constructor( public name: string, private password: string, protected id: number ) {} } // 避免冗余代码 class UserVerbose { name: string; private password: string; protected id: number; constructor(name: string, password: string, id: number) { this.name = name; this.password = password; this.id = id; } } ``` 3. **使用存取器控制属性访问**: ```typescript class Product { private _price: number = 0; get price(): number { return this._price; } set price(value: number) { if (value >= 0) { this._price = value; } else { throw new Error("Price cannot be negative"); } } } ``` ## 常见问题 1. **构造函数重载**: ```typescript class Database { constructor(config: string); constructor(config: { host: string; port: number }); constructor(config: unknown) { if (typeof config === "string") { // 处理字符串配置 } else { // 处理对象配置 } } } ``` 2. **私有字段vs私有属性**: ```typescript class Example { #truePrivate: string; // ECMAScript私有字段 private tsPrivate: string; // TypeScript私有属性 constructor() { this.#truePrivate = "truly private"; this.tsPrivate = "compile-time private"; } } ``` ## 下一步 掌握了类的基本定义后,你可以: 1. 学习类的继承和多态 2. 探索更多访问修饰符的使用 3. 实践面向对象设计模式 4. 了解装饰器的应用 通过合理使用类,你可以构建出结构清晰、易于维护的面向对象程序。