返回
TypeScript 类的继承和基本类型指定
前端
2023-12-26 02:41:18
类的继承
面向对象编程(OOP)中,继承是类与类之间的关系,它允许子类从父类继承属性和方法。在 TypeScript 中,类的继承通过 extends
实现。
class Parent {
// 属性和方法
}
class Child extends Parent {
// 属性和方法
}
子类可以访问父类的属性和方法,并且可以重写父类的方法。子类也可以定义自己的属性和方法。
基本类型指定
在 TypeScript 中,类的属性和方法可以指定基本类型。基本类型包括:
- 数字(
number
) - 字符串(
string
) - 布尔值(
boolean
) - 数组(
array
) - 元组(
tuple
) - 枚举(
enum
) - 空值(
void
) undefined
null
基本类型指定有助于提高代码的可读性和可维护性,并可以帮助 TypeScript 编译器进行类型检查。
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('John Doe', 30);
person.greet(); // Hello, my name is John Doe and I am 30 years old.
超类构造函数
在 TypeScript 中,子类在构造函数中必须调用父类的构造函数,否则会提示错误。
class Parent {
constructor(name: string) {
console.log(`Parent constructor called with name: ${name}`);
}
}
class Child extends Parent {
constructor(name: string) {
// 调用父类的构造函数
super(name);
console.log(`Child constructor called with name: ${name}`);
}
}
const child = new Child('John Doe');
/*
输出:
Parent constructor called with name: John Doe
Child constructor called with name: John Doe
*/
修饰符
TypeScript 中提供了三个修饰符:公共(public
)、私有(private
)和受保护(protected
)。
- 公共修饰符(public) :允许从任何地方访问类、属性和方法。
- 私有修饰符(private) :只能在类内部访问属性和方法。
- 受保护修饰符(protected) :允许在类内部和派生类中访问属性和方法。
class Person {
private name: string; // 私有属性
protected age: number; // 受保护属性
public greet() { // 公共方法
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
}
class Employee extends Person {
public salary: number; // 公共属性
constructor(name: string, age: number, salary: number) {
super(name);
this.age = age; // 可以访问父类的受保护属性
this.salary = salary;
}
public getSalary() { // 公共方法
return this.salary;
}
}
const employee = new Employee('John Doe', 30, 100000);
employee.greet(); // Hello, my name is John Doe and I am 30 years old.
console.log(employee.getSalary()); // 100000
// 尝试访问私有属性和方法会报错
console.log(employee.name); // Error: Property 'name' is private and only accessible within class 'Person'.
employee.age = 40; // Error: Property 'age' is protected and only accessible within class 'Person' and its subclasses.
结语
在 TypeScript 中,类的继承和基本类型指定是两个非常重要的概念。掌握这些概念可以帮助您编写出更健壮、更可维护的代码。