如何在 TypeScript 中声明一个类?
在TypeScript中声明一个类主要涉及使用关键字 class,然后定义类的构造函数、属性和方法。下面是一个简单的例子:class Person { // 属性 name: string; age: number; // 构造函数 constructor(name: string, age: number) { this.name = name; this.age = age; } // 方法 describe(): string { return `我是${this.name}, 今年${this.age}岁。`; }}// 使用类创建对象let person1 = new Person("张三", 30);console.log(person1.describe()); // 输出: 我是张三, 今年30岁。类的主要组成部分:属性:用于定义类的特征,如上例中的 name 和 age。构造函数 (constructor):是一种特殊的方法,主要用来在创建对象时初始化对象,为对象成员变量赋初始值。方法:定义类的行为,如 describe 方法用来提供一个人的描述。类的高级特性:继承:使用 extends 关键字,子类可以继承父类的属性和方法。访问修饰符:如 public(公共的)、private(私有的)、protected(受保护的)等,用来限制访问范围。静态属性和方法:使用 static 关键字,这些属性和方法属于类本身,而不是类的实例。例如,扩展上面的例子来添加一个继承的类和使用访问修饰符:class Employee extends Person { private salary: number; // 私有属性,外部不能直接访问 constructor(name: string, age: number, salary: number) { super(name, age); // 调用父类的构造函数 this.salary = salary; } describe(): string { // 覆盖父类的方法 return `${super.describe()},我的工资是${this.salary}元。`; } // 静态方法 static isEmployee(obj: any): obj is Employee { return obj instanceof Employee; }}let employee1 = new Employee("李四", 40, 5000);console.log(employee1.describe()); // 输出: 我是李四, 今年40岁,我的工资是5000元。console.log(Employee.isEmployee(employee1)); // 输出: true这个例子展示了如何在TypeScript中使用类、继承、访问修饰符以及静态方法。