TypeScript中类与接口的面向对象编程
立即解锁
发布时间: 2025-09-05 00:12:26 阅读量: 5 订阅数: 15 AIGC 

### TypeScript 中类与接口的面向对象编程
#### 1. 多态与方法重载
在编程中,多态是面向对象语言的一个重要特性。例如,在处理不同类型的对象时,代码可能会遍历 `Person` 类型的对象并调用 `Person.promote()` 方法。但实际上,这些对象可能是 `Employee` 类型,也可能是 `Contractor` 类型。对象的实际类型只有在运行时才会被评估,这就是为什么每个对象都能正确调用 `increasePay()` 方法的原因。
方法重载是指一个类可以声明多个同名但参数不同的方法。像 Java 和 C# 这样的面向对象编程语言都支持方法重载。例如,`calculateTax()` 方法可以有两个版本,一个接受两个参数(如个人收入和受抚养人数),另一个接受一个 `Customer` 类型的参数。
在强类型语言中,方法重载非常重要,因为不能随意调用类方法并提供任意类型的参数,而且参数的数量也可能不同。而 TypeScript 是 JavaScript 的语法糖,JavaScript 允许在调用函数时传递比函数签名声明更多或更少的参数,并且不会报错。不过,TypeScript 提供了一种语法来显式声明每个允许的重载方法签名,从而避免运行时的意外错误。
下面是一个错误的方法重载示例:
```typescript
class ProductService {
getProducts() {
console.log(`Getting all products`);
}
getProducts(id: number) { // error
console.log(`Getting the product info for ${id}`);
}
}
const prodService = new ProductService();
prodService.getProducts(123);
prodService.getProducts();
```
上述代码会导致 TypeScript 编译器报错,提示 “Duplicate function implementation”。因为在 JavaScript 中,第二个 `getProducts` 方法会覆盖第一个,运行时只有一个版本的 `getProducts(id)` 方法。
正确的方法重载语法如下:
```typescript
class ProductService {
getProducts(): void;
getProducts(id: number): void;
getProducts(id?: number) {
if (typeof id === 'number') {
console.log(`Getting the product info for ${id}`);
} else {
console.log(`Getting all products`);
}
}
}
const prodService = new ProductService();
prodService.getProducts(123);
prodService.getProducts();
```
在这个示例中,注意实现方法中 `id` 参数后面的问号,它将该参数声明为可选参数。如果不将其声明为可选参数,编译器会报错 “Overload signature is not compatible with function implementation”。
方法重载还可以用于指示方法不仅可以有不同的参数,还可以返回不同类型的值。例如:
```typescript
interface Product {
id: number;
description: string;
}
class ProductService {
getProducts(description: string): Product[];
getProducts(id: number): Product;
getProducts(product: number | string): Product[] | Product{
if (typeof product === "number") {
console.log(`Getting the product info for id ${product}`);
return { id: product, description: 'great product' };
} else if (typeof product === "string") {
console.log(`Getting product with description ${product}`);
return [{ id: 123, description: 'blue jeans' },
{ id: 789, description: 'blue jeans' }];
} else {
return { id: -1,
description: 'Error: getProducts() accept only number or string as args' };
}
}
}
const prodService = new ProductService();
console.log(prodService.getProducts(123));
console.log(prodService.getProducts('blue jeans'));
```
虽然可以通过联合类型来实现类似的功能,但方法重载有助于 TypeScript 编译器将提供的参数类型正确映射到返回值类型,并且在使用 IDE 时能提供更好的自动补全选项。
#### 2. 构造函数重载
在 TypeScript 类中,构造函数只能有一个名称 `constructor`。如果想创建一个具有多个不同签名构造函数的类,可以使用重载语法。例如:
```typescript
class Product {
id: number;
description: string;
constructor();
constructor(id: number);
constructor(id: number, description: string);
constructor(id?: number, description?: string) {
// Constructor implementation goes here
}
}
```
不过,重载构造函数并不是初始化对象属性的唯一方法。也可以声明一个接口来表示构造函数的所有可能参数。例如:
```typescript
interface ProductProperties {
id?: number;
description?: string;
}
class Product {
id: number;
description: string;
constructor(properties?: ProductProperties ) {
// Constructor implementation goes here
}
}
```
在 TypeScript 中重载方法或构造函数时,要运用常识。虽然重载提供了多种调用方法的方式,但逻辑可能很快变得难以理解。在日常的 TypeScript 工作中,很少使用重载。
#### 3. 使用接口
在之前的学习中,我们使用 TypeScript 接口仅用于声明自定义类型。一般规则是:如果需要一个包含构造函数的自定义类型,使用类;否则使用接口。接下来,我们将展示如何使用 TypeScript 接口来确保一个类实现特定的 API。
##### 3.1 强制执行契约
接口不仅可以声明属性,还可以声明方法(但不包含实现)。类声明可以使用 `implements` 关键字后跟接口名称。这意味着接口只包含方法签名,而类可以包含这些方法的实现。
例如,以汽车为例,一辆丰田凯美瑞有数千个部件执行各种操作,但作为司机,只需要知道如何使用少数几个控件,如启动和停止发动机、加速和刹车、打开收音机等。这些控件可以看作是丰田凯美瑞设计师提供给司机的公共接口。
现在,我们使用 TypeScript 语法来建模汽车接口。以下是一个 `MotorVehicle` 接口,声明了五个方法:
```typescript
interface MotorVehicle {
startEngine(): boolean;
stopEngine(): boolean;
brake(): boolean;
accelerate(speed: number): void;
hon
```
0
0
复制全文
相关推荐









