TypeScript 类
在TypeScript中,类(Class)是一种面向对象编程的核心概念,它允许创建具有属性和方法的蓝图,用于实例化对象。类在TypeScript中不仅可以定义对象的结构,还可以包含构造函数、实例方法、静态方法等。
类的定义:
类的定义使用 class 关键字,后跟类名,并使用大括号 {} 包含类的成员(属性和方法)。
实例化类:
通过使用 new 关键字,可以实例化一个类,并创建一个对象。
构造函数: 类的构造函数是一个特殊的方法,在实例化类时自动调用。它用于初始化对象的属性。例如:
class Rectangle {
width: number;
height: number;
constructor(width: number, height: number) {
this.width = width;
this.height = height;
}
getArea(): number {
return this.width * this.height;
}
}
const rect = new Rectangle(5, 10);
console.log(rect.getArea()); // 输出 50
实例方法:
类中的实例方法可以访问对象的属性,并在对象上执行操作。例如:
class Counter {
count: number = 0;
increment(): void {
this.count++;
}
decrement(): void {
this.count--;
}
}
const counter = new Counter();
counter.increment();
counter.increment();
console.log(counter.count); // 输出 2
静态方法: 静态方法是类的方法,不需要实例化即可调用。它们通常用于执行与类相关的操作,而不是与实例相关的操作。
继承: TypeScript中的类支持继承,子类可以继承父类的属性和方法,并可以添加自己的属性和方法。例如:
class Student extends Person {
studentId: number;
constructor(firstName: string, lastName: string, studentId: number) {
super(firstName, lastName); // 调用父类的构造函数
this.studentId = studentId;
}
}
const student = new Student("Alice", "Smith", 12345);
console.log(student.getFullName()); // 输出 "Alice Smith"
console.log(student.studentId); // 输出 12345
TypeScript泛型
在TypeScript中,泛型(Generics)是一种强大的特性,它允许在定义函数、类或接口的时候使用类型参数,从而增加代码的灵活性和重用性。泛型能够在多种数据类型上工作,而不需要针对每种类型都创建重复的代码。
泛型的使用方法和场景:
-
函数泛型: 使用泛型可以编写可以适用于不同数据类型的函数,增加代码的重用性。例如,一个用于交换两个变量值的函数可以使用泛型:
function swap<T>(a: T, b: T): void { let temp: T = a; a = b; b = temp; } let x = 5; let y = 10; swap(x, y); // 此时 x 为 10,y 为 5 -
类泛型: 泛型也可以用于类的定义,使得类可以在多种数据类型上工作。
-
接口泛型: 使用泛型还可以定义可适用于不同数据类型的接口,增加代码的灵活性。例如,一个泛型的键值对接口:
`interface KeyValuePair<K, V> { key: K; value: V; } const numberPair: KeyValuePair<string, number> = { key: "age", value: 25 }; const stringPair: KeyValuePair<string, string> = { key: "name", value: "Alice" }; `
##使用类型约束增加代码的灵活性和安全性:
有时,可能希望对泛型的类型范围进行限制,以增加代码的安全性。这可以通过类型约束(Type Constraints)来实现。 例如编写一个函数,从数组中找到最大值。为了实现这一点,可以使用类型约束来确保数组元素是可比较的:
function findMax<T extends number | string>(arr: T[]): T | undefined {
if (arr.length === 0) return undefined;
let max: T = arr[0];
for (const item of arr) {
if (item > max) {
max = item;
}
}
return max;
}
const numbers = [1, 5, 3, 9];
console.log(findMax(numbers)); // 输出 9
const strings = ["apple", "banana", "orange"];
console.log(findMax(strings)); // 输出 "orange"
在上述示例中,通过使用类型约束 T extends number | string,我们限制了函数的参数只能是 number 或 string 类型,从而确保比较的正确性。
总之,TypeScript中的泛型可以在函数、类和接口中提供强大的灵活性和代码重用性。通过使用类型约束,你可以更精确地定义泛型的行为,从而增加代码的安全性。