TypeScript 中的类(Class)详解
TypeScript 的类(class)基于 ES6 类语法,并添加了强大的静态类型支持、访问修饰符、抽象类、装饰器等特性,使其更接近传统面向对象语言(如 Java/C#),同时完全兼容 JavaScript。
1. 基本类声明与实例化
classPerson{name:string;// 实例属性(需手动声明)age:number;constructor(name:string,age:number){this.name=name;this.age=age;}greet():void{console.log(`Hello, I'm${this.name}`);}}letalice=newPerson("Alice",30);alice.greet();// "Hello, I'm Alice"参数属性简写(推荐,减少冗余):
classPerson{constructor(publicname:string,// 自动声明 public name 并赋值privateage:number// 自动声明 private age 并赋值){}greet():void{console.log(`Hello, I'm${this.name}`);// console.log(this.age); // OK,在类内部可访问}}letbob=newPerson("Bob",25);console.log(bob.name);// OK// console.log(bob.age); // 错误:private2. 访问修饰符(Access Modifiers)
| 修饰符 | 作用范围 | 示例 |
|---|---|---|
public | 默认,所有地方可访问 | public name: string |
private | 仅类内部可访问 | private secret: string |
protected | 类内部及子类可访问 | protected familyName: string |
readonly | 只读(不能重新赋值,可结合以上) | readonly id: number |
classEmployee{constructor(publicname:string,privatesalary:number,protecteddepartment:string,readonlyid:number){}getInfo(){console.log(this.salary);// OKconsole.log(this.department);// OK}}classManagerextendsEmployee{manage(){// console.log(this.salary); // 错误:privateconsole.log(this.department);// OK:protected}}3. 静态成员(Static Members)
属于类本身,而不是实例:
classMathUtils{staticPI:number=3.14159;staticcircleArea(radius:number):number{returnthis.PI*radius**2;}}console.log(MathUtils.PI);// 3.14159console.log(MathUtils.circleArea(5));// 通过类名调用4. 类继承(Extends)与 super
classAnimal{constructor(publicname:string){}move(distance:number=0){console.log(`${this.name}moved${distance}m.`);}}classDogextendsAnimal{constructor(name:string,publicbreed:string){super(name);// 必须调用 super()}bark(){console.log("Woof!");}move(distance:number=5){super.move(distance);// 调用父类方法console.log("Dog is running!");}}letdog=newDog("Buddy","Golden");dog.bark();dog.move();// 先调用 Animal.move,再输出 "Dog is running!"5. 抽象类(Abstract Class)
不能直接实例化,用于定义子类必须实现的成员:
abstractclassShape{abstractgetArea():number;// 抽象方法,必须在子类实现move(x:number,y:number){console.log(`Moved to (${x},${y})`);}}classCircleextendsShape{constructor(publicradius:number){super();}getArea():number{returnMath.PI*this.radius**2;}}letcircle=newCircle(10);console.log(circle.getArea());// let shape = new Shape(); // 错误:不能实例化抽象类6. 类实现接口(Implements)
类可以实现一个或多个接口:
interfacePrintable{print():void;}interfaceLoggable{log(message:string):void;}classDocumentimplementsPrintable,Loggable{constructor(publictitle:string){}print(){console.log(`Printing${this.title}`);}log(message:string){console.log(`[${this.title}]${message}`);}}7. getter / setter
classRectangle{constructor(private_width:number,private_height:number){}getarea():number{returnthis._width*this._height;}setwidth(value:number){if(value<=0)thrownewError("宽度必须正数");this._width=value;}}letrect=newRectangle(10,5);console.log(rect.area);// 50(调用 getter)rect.width=20;// 调用 setter8. 类作为类型使用
classCar{constructor(publicbrand:string){}}letmyCar:Car=newCar("Tesla");functiondrive(vehicle:Car){console.log(`Driving${vehicle.brand}`);}9. 装饰器(Decorators)—— 实验性特性(需启用experimentalDecorators)
常用于框架(如 Angular、NestJS):
functionsealed(target:Function){Object.seal(target);Object.seal(target.prototype);}@sealedclassGreeter{greeting:string;constructor(message:string){this.greeting=message;}}10. 最佳实践建议
| 建议 | 说明 |
|---|---|
| 使用参数属性简写 | 减少 constructor 冗余 |
优先使用private和readonly | 封装性更好 |
| 抽象类用于定义通用行为 | 强制子类实现关键方法 |
| 接口 + 类组合使用 | 接口定义合约,类实现细节 |
| 静态成员用于工具方法/常量 | 如配置、工厂方法 |
开启strictPropertyInitialization | 强制非 undefined 属性在 constructor 初始化 |
小结:类特性速查表
| 特性 | 语法示例 |
|---|---|
| 基本类 | class Person { constructor(public name: string) {} } |
| 访问修饰符 | private age: number |
| 静态成员 | static count: number = 0 |
| 继承 | class Dog extends Animal {} |
| 抽象类/方法 | abstract class Shape { abstract draw(): void; } |
| 实现接口 | class User implements Printable {} |
| getter/setter | get fullName(): string { return ... } |
TypeScript 的类系统结合了现代 JS 的灵活性和强类型检查,是构建大型、可维护应用的核心工具,尤其在 Angular、NestJS 等框架中广泛使用。
如果您想深入某个部分(如泛型类、装饰器实战、类与模块的结合、或设计模式实现),请告诉我!