在 TypeScript 中,类(Class) 是面向对象编程(OOP)的核心概念之一。它扩展了 JavaScript 的 class
语法,同时引入了访问修饰符、构造函数参数类型、接口实现等类型系统特性,使代码更加健壮和可维护。
目录
- 类的基本概念
- 类的构造函数
- 类的访问修饰符
- 类的继承(继承与重写)
- 抽象类(
abstract
) - 类与接口的结合使用
- 静态成员(
static
) - 类的 Getter 和 Setter
- 泛型类
- 最佳实践
- 参考资料
1. 类的基本概念
TypeScript 的 class
语法类似于 JavaScript,但它提供了更严格的类型检查:
class Person {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
greet() {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
}
const person = new Person("Alice", 25);
person.greet(); // 输出: Hello, my name is Alice and I am 25 years old.
2. 类的构造函数
类的 constructor
负责初始化对象,在创建实例时自动调用:
class Car {
brand: string;
model: string;
constructor(brand: string, model: string) {
this.brand = brand;
this.model = model;
}
display() {
console.log(`Car: ${this.brand} ${this.model}`);
}
}
const car = new Car("Tesla", "Model S");
car.display(); // 输出: Car: Tesla Model S
注意: 构造函数的参数可以直接赋值给类属性(见访问修饰符部分)。
3. 类的访问修饰符
TypeScript 提供了 public
、private
和 protected
三种修饰符:
修饰符 | 作用 |
---|---|
public | 默认修饰符,类的内部和外部都可以访问 |
private | 只能在类内部访问,不能在类外部访问 |
protected | 只能在类内部和子类访问,不能在类实例外访问 |
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 getAge(): number {
return this.age; // ✅ 允许访问
}
}
const animal = new Animal("Lion", 5, "Mammal");
console.log(animal.name); // ✅ 公开属性可访问
// console.log(animal.age); // ❌ 报错:私有属性不能在外部访问
// console.log(animal.type); // ❌ 报错:受保护属性不能在实例外访问
简写方式(构造函数参数自动赋值)
class Employee {
constructor(public name: string, private salary: number) {}
getSalary(): number {
return this.salary;
}
}
4. 类的继承(继承与重写)
使用 extends
关键字实现类的继承,子类可以重写(override)父类的方法:
class Animal {
name: string;
constructor(name: string) {
this.name = name;
}
makeSound() {
console.log("Some generic sound");
}
}
class Dog extends Animal {
constructor(name: string) {
super(name); // 调用父类构造函数
}
makeSound() {
console.log("Woof! Woof!");
}
}
const dog = new Dog("Buddy");
dog.makeSound(); // 输出: Woof! Woof!
super
关键字 用于调用父类的构造函数或方法。
5. 抽象类(abstract
)
抽象类 不能被实例化,只能被继承,且可以定义抽象方法:
abstract class Shape {
abstract getArea(): number; // 抽象方法
}
class Circle extends Shape {
constructor(public radius: number) {
super();
}
getArea(): number {
return Math.PI * this.radius ** 2;
}
}
const circle = new Circle(10);
console.log(circle.getArea()); // 输出: 314.159...
6. 类与接口的结合使用
类可以使用 implements
关键字来实现接口:
interface Logger {
log(message: string): void;
}
class ConsoleLogger implements Logger {
log(message: string) {
console.log("Log:", message);
}
}
const logger = new ConsoleLogger();
logger.log("This is a log message.");
7. 静态成员(static
)
static
关键字用于定义静态属性和方法,无需实例化即可访问:
class MathUtils {
static PI = 3.14159;
static square(x: number): number {
return x * x;
}
}
console.log(MathUtils.PI); // 输出: 3.14159
console.log(MathUtils.square(4)); // 输出: 16
8. 类的 Getter 和 Setter
get
和 set
关键字可以定义访问器:
class User {
private _password: string = "";
get password(): string {
return "****"; // 隐藏实际密码
}
set password(value: string) {
if (value.length >= 6) {
this._password = value;
} else {
console.log("Password too short!");
}
}
}
const user = new User();
user.password = "12345"; // 输出: Password too short!
user.password = "securePassword"; // ✅
console.log(user.password); // 输出: ****
9. 泛型类
使用 泛型(Generics) 可以让类支持多种数据类型:
class Box<T> {
content: T;
constructor(content: T) {
this.content = content;
}
getContent(): T {
return this.content;
}
}
const stringBox = new Box<string>("Hello");
console.log(stringBox.getContent()); // 输出: Hello
10. 最佳实践
✅ 使用 private
和 protected
限制访问范围,增强封装性。
✅ 使用 readonly
修饰符 避免不必要的修改。
✅ 优先使用 implements
而非 extends
,遵循接口优先原则。
✅ 使用 get
/set
保护数据,避免直接暴露敏感信息。
11. 参考资料
- TypeScript 官方文档:Classes
- MDN 文档:JavaScript Class
- TypeScript 深入指南:TypeScript Deep Dive
TypeScript 的类提供了 JavaScript 原生 class
的强大扩展,结合接口、访问修饰符和泛型,使 OOP 编程更加强大和类型安全。
发表回复