在TS中,
class
是一种创建对象的蓝图,它封装了数据(属性)和操作数据的方法。它的语法和面向对象编程(OOP)中的类非常相似,但 TS 提供了更强的类型检查和一些独有的特性。
1.class的基本语法
一个基本的
class
类定义通常包括以下几个部分:(1)属性(properties):类的成员变量,用来存储数据;
(2)构造函数(constructor):一个特殊的方法,在实例化类的时候自动调用,用于初始化类的属性;
(3)方法(methods):类的成员函数,用来定义行为;
(4)修饰符(modifiers):用来控制类成员的可见性和行为。
举个栗子
ts
class Animal {
// 属性,可以带类型注解
name: string;
species: string;
// 构造函数,用于初始化实例
constructor(name: string, species: string) {
this.name = name;
this.species = species;
}
// 方法
makeSound(sound: string): void {
console.log(`${this.name} (${this.species}) says: ${sound}`);
}
}
// 创建类的实例
const dog = new Animal("Buddy", "Dog");
// 调用方法
dog.makeSound("Woof!"); // 输出: Buddy (Dog) says: Woof!
2.类中常见的修饰符
(1)public(默认):成员在类的内部,子类和实例外都能被访问;
(2)private:成员只能在类的内部被访问;
(3)protected:成员可以在类的内部和子类中访问,但不能在类的实例外部访问;
(4)readonly:属性只能在声明时或构造函数中被赋值,之后不能被修改。
举个栗子
ts
class Car {
public brand: string;
private secretKey: string; // 只能在 Car 类内部访问
protected year: number; // 可以在子类中访问
readonly chassisNumber: string; // 只能在构造函数中赋值
constructor(brand: string, year: number, chassisNumber: string) {
this.brand = brand;
this.year = year;
this.chassisNumber = chassisNumber;
this.secretKey = "160722";
}
getSecretKey(): string {
return this.secretKey; // 在类内部可以访问 private 属性
}
}
class SportsCar extends Car {
constructor(brand: string, year: number, chassisNumber: string) {
// 必须在子类构造函数中调用 super() 来调用父类的构造函数
super(brand, year, chassisNumber);
console.log(`The car was made in ${this.year}`); // 在子类中可以访问 protected 属性
}
}
const myCar = new Car("xiaomiSU7", 2025, "云A12345");
console.log(myCar.brand); // xiaomiSU7
// console.log(myCar.secretKey); // 错误: Property 'secretKey' is private
// myCar.chassisNumber = "NewVIN"; // 错误: Cannot assign to 'chassisNumber' because it is a read-only property.
3.static修饰符
用static 定义的属性(函数),不可以通过
this
去访问,只能通过类名去调用。static之间可以互相访问,静态成员是"属于类,而非对象"的。当你需要一个不依赖于对象状态,或用于创建、管理对象的通用功能时,就应该考虑使用静态属性或函数。这有助于将类的职责分离,并使代码更加模块化和易于管理。例如独立于实例的通用功能,工厂方法,单例模式。
举个栗子:工具类,数据库,config等
ts
class Config {
static DATABASE_URL: string = 'http://db.example.com';
static API_KEY: string = 'xyz123';
}
// 直接使用,无需实例化
console.log(Config.DATABASE_URL);
静态方法可以作为
工厂
,用于创建类的实例。这种模式通常被称为静态工厂方法。
ts
class User {
id: number;
username: string;
constructor(id: number, username: string) {
this.id = id;
this.username = username;
}
static createByUsername(username: string) {
// 假设这里根据用户名从数据库获取ID
const id = 1;
return new User(id, username);
}
static createById(id: number) {
// 假设这里根据ID从数据库获取用户名
const username = '...';
return new User(id, username);
}
}
const user1 = User.createByUsername('Alice');
const user2 = User.createById(123);
console.log(user1, user2);//User { id: 1, username: 'Alice' } User { id: 123, username: '...' }
4.interface 定义类
interface(接口)是 TypeScript 中一个强大的特性,主要用于定义对象的
结构和约束
。它只存在于编译时(compile-time),在编译成 JavaScript 代码后会被完全移除,因此不会增加任何运行时开销。
遵循接口定义的对象,缺少或多属性都会报错
ts
interface UserI {
id: number;
name: string;
email: string;
}
const user: UserI = {
id: 1,
name: "YaeZed",
email: "yaezed@qq.com"
};
接口继承,使用
extends
关键字
ts
interface Shape {
color: string;
}
interface Square extends Shape {
sideLength: number;
}
const square: Square = {
color: "blue",
sideLength: 10
};
interface 的主要作用是定义数据结构和实现类型检查
ts
interface UserProfile {
id: number;
username: string;
avatarUrl: string;
lastLoginTime: Date;
}
const fetchUserProfile = async (userId: number): Promise<UserProfile> => {
const reponse = await fetch(`https://api.example.com/users/${userId}`);
return await reponse.json() as UserProfile;
}
对对象进行解构赋值和参数类型检查,确保传入的对象符合预期
ts
interface Employee {
name: string;
id: number;
department: string;
}
const printEmployeeInfo = (employee: Employee) => {
console.log(`Name: ${employee.name}, ID: ${employee.id}, Department: ${employee.department}`);
}
const emp = { name: "Yae Zed", id: 123, department: "IT" };
printEmployeeInfo(emp);//Name: Yae Zed, ID: 123, Department: IT
类可以使用
implements
关键字来实现一个或多个接口,确保类具有接口中定义的所有属性和方法。这是一种强制性的约束。
ts
interface ILogger {
log(message: string): void;
}
class ConsoleLogger implements ILogger {
log(message: string): void {
console.log(`[LOG] ${message}`);
}
}
const Ilogger = new ConsoleLogger();
Ilogger.log("Hello, world!");//[LOG] Hello, world!
参考文章
小满zs 学习TypeScript8(class类)xiaoman.blog.csdn.net/article/det...