TypeScript 接口:接口继承与实现
TypeScript 接口(Interface)是定义对象结构的强大工具,它规定了对象“长什么样”。通过继承与实现,我们可以复用代码逻辑,构建层次分明、类型严密的系统。
1. 接口继承:扩展已有定义
接口继承允许一个接口从另一个或多个接口中获取属性和方法,从而实现代码复用。这意味着新接口会包含父接口的所有成员,并可以添加自己的特有成员。
1.1 单接口继承
当一个接口需要基于另一个接口进行扩展时,使用 extends 关键字。
- 定义一个基础接口
Animal,包含通用属性。 - 创建一个新接口
Dog,使用extends继承Animal。 - 添加
Dog特有的属性。
interface Animal {
name: string;
age: number;
}
// Dog 继承了 Animal 的 name 和 age
interface Dog extends Animal {
breed: string;
bark(): void;
}
const myDog: Dog = {
name: "旺财",
age: 3,
breed: "金毛",
bark() {
console.log("汪汪!");
}
};
在上述代码中,Dog 接口必须包含 name 和 age,因为它们来自父接口 Animal。
1.2 多接口继承
TypeScript 支持一个接口继承多个接口。这在需要组合多种特性时非常有用。
- 定义
CanFly接口,描述飞行能力。 - 定义
CanSwim接口,描述游泳能力。 - 创建
SuperHero接口,同时继承CanFly和CanSwim。
interface CanFly {
fly(): void;
}
interface CanSwim {
swim(): void;
}
// 多重继承,用逗号分隔
interface SuperHero extends CanFly, CanSwim {
heroName: string;
}
const hero: SuperHero = {
heroName: "海王",
fly() {
console.log("起飞!");
},
swim() {
console.log("潜水!");
}
};
注意:如果被继承的多个接口中存在同名的属性,且类型不兼容,TypeScript 编译器会报错。
2. 接口实现:类的契约
接口定义了“做什么”,而类(Class)负责“怎么做”。使用 implements 关键字,可以强制类必须遵循接口定义的结构。
2.1 基本实现
- 定义
ClockInterface接口,规定时间和格式化方法。 - 创建
DigitalClock类,使用implements关键字。 - 在类中实现接口规定的所有属性和方法。
interface ClockInterface {
currentTime: Date;
setTime(d: Date): void;
}
class DigitalClock implements ClockInterface {
currentTime: Date = new Date();
setTime(d: Date) {
this.currentTime = d;
}
constructor() {}
}
如果 DigitalClock 类缺少 currentTime 属性或 setTime 方法,TypeScript 会立即抛出错误,阻止代码运行。
2.2 实现多个接口
一个类可以实现一个或多个接口,从而具备多种角色的特征。
- 定义
Shape接口,包含颜色属性。 - 定义
Square接口,包含边长属性。 - 编写
ColoredSquare类,同时实现这两个接口。
interface Shape {
color: string;
}
interface Square {
sideLength: number;
}
// 同时实现两个接口
class ColoredSquare implements Shape, Square {
color: string;
sideLength: number;
constructor(color: string, sideLength: number) {
this.color = color;
this.sideLength = sideLength;
}
}
3. 核心区别:extends 与 implements
为了更清晰地理解何时使用继承,何时使用实现,请参考下表。
| 特性 | extends (继承) | implements (实现) |
|---|---|---|
| 使用对象 | 接口 接口 | 类 接口 |
| 目的 | 扩展契约,复用类型定义 | 履行契约,提供具体代码逻辑 |
| 成员来源 | 自动拥有父接口成员 | 必须手动编写代码实现所有成员 |
| 数量支持 | 可继承一个或多个接口 | 可实现一个或多个接口 |
4. 进阶实战:混合类型的继承与实现
在实际开发中,经常遇到接口继承与类实现混合使用的场景。
- 定义
Entity基础接口,包含id字段。 - 定义
Timestamped接口,包含createdAt字段。 - 定义
User接口,继承上述两个接口,并添加username。 - 创建
UserService类,实现User接口。
// 基础实体
interface Entity {
id: string;
}
// 时间戳
interface Timestamped {
createdAt: Date;
}
// 用户接口:组合继承
interface User extends Entity, Timestamped {
username: string;
email: string;
}
// 用户服务类:实现 User 接口
class UserService implements User {
id: string;
createdAt: Date;
username: string;
email: string;
constructor(id: string, username: string, email: string) {
this.id = id;
this.username = username;
this.email = email;
this.createdAt = new Date();
}
// 可以添加额外的方法,但必须包含接口规定的属性
sendEmail() {
console.log(`发送邮件给: ${this.email}`);
}
}
// 实例化
const user = new UserService("001", "admin", "admin@example.com");
通过这种方式,UserService 类被强制要求包含 id、createdAt、username 和 email,确保了数据的完整性。

暂无评论,快来抢沙发吧!