接口可以通过继承来扩展,也可以被类实现。这种机制让我们能够复用类型定义,构建灵活的类型层次结构。
接口继承#
基本继承#
使用 extends 关键字继承接口:
// TypeScript 5.x
// 基础接口interface Animal { name: string age: number}
// 继承接口interface Dog extends Animal { breed: string bark(): void}
// Dog 拥有 Animal 的所有属性,加上自己的属性const dog: Dog = { name: '旺财', age: 3, breed: '柴犬', bark() { console.log('汪汪!') },}多重继承#
接口可以同时继承多个接口:
interface Flyable { fly(): void altitude: number}
interface Swimmable { swim(): void depth: number}
interface Walkable { walk(): void speed: number}
// 继承多个接口interface Duck extends Flyable, Swimmable, Walkable { quack(): void}
const duck: Duck = { altitude: 100, depth: 5, speed: 2, fly() { console.log('飞行中...') }, swim() { console.log('游泳中...') }, walk() { console.log('行走中...') }, quack() { console.log('嘎嘎!') },}继承时覆盖属性#
子接口可以覆盖父接口的属性,但必须兼容:
interface Base { id: string | number name: string}
// ✅ 可以收窄类型interface Derived extends Base { id: number // 从 string | number 收窄为 number}
// ❌ 不能扩展类型// interface Invalid extends Base {// id: string | number | boolean; // 错误// }
// ❌ 不能改变类型// interface Invalid2 extends Base {// name: number; // 错误:与 string 不兼容// }继承与合并的结合#
// 基础接口interface Component { render(): void}
// 通过继承扩展interface ClickableComponent extends Component { onClick(): void}
// 通过合并扩展(同名接口)interface Component { destroy(): void}
// 现在 Component 有 render 和 destroy// ClickableComponent 有 render、destroy 和 onClick类实现接口#
implements 关键字#
类使用 implements 来实现接口:
interface Printable { print(): void}
class Document implements Printable { content: string
constructor(content: string) { this.content = content }
print() { console.log(this.content) }}
const doc = new Document('Hello, World!')doc.print()实现多个接口#
interface Serializable { serialize(): string}
interface Deserializable { deserialize(data: string): void}
interface Cloneable { clone(): this}
// 实现多个接口class User implements Serializable, Deserializable, Cloneable { constructor( public name: string, public age: number ) {}
serialize(): string { return JSON.stringify({ name: this.name, age: this.age }) }
deserialize(data: string): void { const parsed = JSON.parse(data) this.name = parsed.name this.age = parsed.age }
clone(): this { return new (this.constructor as any)(this.name, this.age) }}
const user = new User('张三', 25)console.log(user.serialize()) // {"name":"张三","age":25}const clone = user.clone()接口与类的属性#
interface Person { name: string age: number greet(): void}
// 类必须实现接口的所有成员class Employee implements Person { // 可以用构造函数简写 constructor( public name: string, public age: number, public department: string // 可以有额外属性 ) {}
greet() { console.log(`我是 ${this.name},来自 ${this.department}`) }
// 可以有额外方法 work() { console.log('工作中...') }}可选成员的实现#
interface Config { host: string port: number ssl?: boolean // 可选 timeout?: number // 可选}
class ServerConfig implements Config { host: string port: number ssl?: boolean // 可以实现也可以不实现
constructor(host: string, port: number, ssl?: boolean) { this.host = host this.port = port this.ssl = ssl // timeout 不需要实现 }}接口继承类#
TypeScript 中接口可以继承类:
class Control { private state: boolean = false
activate() { this.state = true }}
// 接口继承类,包括私有成员interface SelectableControl extends Control { select(): void}
// 只有 Control 的子类才能实现这个接口class Button extends Control implements SelectableControl { select() { console.log('Button selected') }}
class TextBox extends Control implements SelectableControl { select() { console.log('TextBox selected') }}
// ❌ 这个类没有继承 Control,无法实现接口// class Image implements SelectableControl {// select() { } // 错误:缺少 private state// }实际应用模式#
仓储模式#
// 基础仓储接口interface Repository<T> { findById(id: string): Promise<T | null> findAll(): Promise<T[]> save(entity: T): Promise<T> delete(id: string): Promise<void>}
// 扩展接口interface UserRepository extends Repository<User> { findByEmail(email: string): Promise<User | null> findByRole(role: string): Promise<User[]>}
// 实现class MongoUserRepository implements UserRepository { async findById(id: string) { /* MongoDB 查询 */ return null } async findAll() { return [] } async save(user: User) { return user } async delete(id: string) {} async findByEmail(email: string) { return null } async findByRole(role: string) { return [] }}插件系统#
// 基础插件接口interface Plugin { name: string version: string install(): void uninstall(): void}
// 扩展接口interface ConfigurablePlugin extends Plugin { configure(options: Record<string, unknown>): void}
interface LifecyclePlugin extends Plugin { onStart(): void onStop(): void}
// 完整插件interface FullPlugin extends ConfigurablePlugin, LifecyclePlugin { getStatus(): 'active' | 'inactive' | 'error'}
// 实现class AnalyticsPlugin implements FullPlugin { name = 'analytics' version = '1.0.0' private status: 'active' | 'inactive' | 'error' = 'inactive'
install() { console.log('Installing analytics...') } uninstall() { console.log('Uninstalling analytics...') } configure(options: Record<string, unknown>) { console.log('Configuring with:', options) } onStart() { this.status = 'active' } onStop() { this.status = 'inactive' } getStatus() { return this.status }}组件接口#
// 基础组件interface Component { render(): string}
// 有状态组件interface StatefulComponent<S> extends Component { state: S setState(newState: Partial<S>): void}
// 有生命周期的组件interface LifecycleComponent extends Component { componentDidMount(): void componentWillUnmount(): void}
// 完整组件interface FullComponent<S> extends StatefulComponent<S>, LifecycleComponent {}
// 抽象基类实现部分功能abstract class BaseComponent<S> implements FullComponent<S> { state: S
constructor(initialState: S) { this.state = initialState }
setState(newState: Partial<S>) { this.state = { ...this.state, ...newState } this.render() // 重新渲染 }
abstract render(): string abstract componentDidMount(): void abstract componentWillUnmount(): void}常见问题#
🙋 接口继承和类型交叉有什么区别?#
// 接口继承:有继承关系,支持覆盖interface A { x: string}interface B extends A { y: number}
// 类型交叉:简单合并type A2 = { x: string }type B2 = A2 & { y: number }
// 主要区别:// 1. 接口可以合并声明,type 不行// 2. 接口继承时冲突会报错,交叉会变成 never// 3. 接口有更好的错误提示🙋 类可以实现 type 定义的类型吗?#
可以:
type Printable = { print(): void}
class Document implements Printable { print() { console.log('Printing...') }}🙋 如何确保类完全实现接口?#
TypeScript 会自动检查,缺少任何成员都会报错:
interface Animal { name: string speak(): void}
// ❌ 错误:缺少 speak 方法// class Cat implements Animal {// name = 'Cat';// }
// ✅ 正确class Cat implements Animal { name = 'Cat' speak() { console.log('Meow!') }}总结#
| 特性 | 语法 | 用途 |
|---|---|---|
| 单继承 | interface B extends A | 扩展单个接口 |
| 多继承 | interface C extends A, B | 组合多个接口 |
| 类实现 | class X implements A | 类遵循接口契约 |
| 多实现 | class X implements A, B | 类实现多个接口 |
| 接口继承类 | interface I extends Class | 继承类的成员类型 |
下一篇我们将学习 TypeScript 中的类基础,包括属性、方法和构造函数。