当涉及到编写可维护、可扩展且类型安全的JavaScript代码时,TypeScript是一个强大的选择。其中,TypeScript中的类和泛型是两个关键概念,可以使代码更具灵活性和安全性。本篇笔记将深入探讨TypeScript中的类和泛型的使用方法和场景,并展示如何使用类型约束来提高代码质量。
类的使用
1. 基本类定义
在TypeScript中,可以使用class关键字定义类。类允许你封装数据和方法,提高了代码的组织性。
class Person {
constructor(public name: string, public age: number) {}
sayHello() {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
}
const person = new Person("Alice", 30);
person.sayHello(); // 输出: Hello, my name is Alice and I am 30 years old.
2. 类继承和抽象类
TypeScript支持类之间的继承,你可以通过extends关键字创建子类,并使用super关键字调用父类的构造函数和方法。
class Student extends Person {
constructor(name: string, age: number, public studentId: string) {
super(name, age);
}
study() {
console.log(`${this.name} with student ID ${this.studentId} is studying.`);
}
}
const student = new Student("Bob", 25, "12345");
student.sayHello(); // 输出: Hello, my name is Bob and I am 25 years old.
student.study(); // 输出: Bob with student ID 12345 is studying.
3. 访问修饰符
TypeScript支持公有、私有和受保护的访问修饰符,用于控制类成员的可见性和访问权限。
class Animal {
private isAlive: boolean = true;
protected type: string = "Unknown";
constructor(public name: string) {}
makeSound() {
console.log(`${this.name} makes a sound.`);
}
}
class Dog extends Animal {
constructor(name: string) {
super(name);
this.type = "Dog";
}
bark() {
console.log(`${this.name} barks.`);
}
}
const dog = new Dog("Buddy");
dog.makeSound(); // 正常,因为makeSound是公有的
console.log(dog.isAlive); // 错误,因为isAlive是私有的
console.log(dog.type); // 正常,因为type是受保护的
泛型的使用
1. 基本泛型
泛型允许你编写可复用的函数和类,同时保持类型安全。你可以使用<T>来声明泛型类型参数。
function identity<T>(value: T): T {
return value;
}
const result = identity("Hello, TypeScript"); // result的类型为string
2. 泛型类
你还可以创建泛型类,以便在类中使用泛型类型参数。
3. 泛型约束
泛型约束允许你限制泛型类型参数的类型范围,以增加类型安全性。
泛型的使用场景
- 数据结构的抽象化:泛型可以用于创建通用的数据结构,如栈、队列和链表。
- 函数工具:泛型函数可以用于编写通用的工具函数,如
map、filter和reduce。 - 跨类型操作:当你需要操作多种类型的数据时,泛型提供了一种统一的方式来处理它们。
- 类型安全:泛型可以捕获并防止类型错误,使代码更加健壮。
总结
TypeScript中的类和泛型是强大的工具,可以提高代码的可维护性、可扩展性和类型安全性。通过合理使用类继承和泛型约束,可以编写更具表现力和可读性的代码。了解这些概念并在实际项目中灵活应用它们,将帮助构建高质量的TypeScript应用程序。