在 TypeScript 中,implements
关键字用于强制类符合一个或多个接口的结构。
以下是其用法及注意事项的详细介绍:
基本用法
-
单个接口实现
类需实现接口中定义的所有必选属性和方法:typescriptinterface Animal { name: string; speak(): void; } class Dog implements Animal { name: string; // 必须实现 constructor(name: string) { this.name = name; } speak() { // 必须实现 console.log("Woof!"); } }
-
实现多个接口
用逗号分隔多个接口,类需满足所有接口要求:typescriptinterface CanRun { run(): void; } interface CanSwim { swim(): void; } class Duck implements CanRun, CanSwim { run() { /* ... */ } // 实现 CanRun swim() { /* ... */ } // 实现 CanSwim }
注意事项
-
严格匹配接口结构
- 必须实现接口中所有非可选属性和方法,否则编译报错。
- 方法签名(参数类型、返回值类型、可选性)需一致:typescript
interface Greeter { greet(name?: string): void; } class EnglishGreeter implements Greeter { greet(name?: string) { // 正确:参数可选 console.log(`Hello, ${name ?? 'Guest'}`); } }
-
可见性一致
接口成员默认public
,实现时不可改为private
或protected
:typescriptinterface IUser { id: number; } class User implements IUser { private id: number; // 错误:接口要求 public }
-
可选属性/方法
可选成员(如age?: number
)在类中可省略,但若实现则需匹配类型。 -
静态成员不受检查
implements
仅检查实例成员,不验证静态成员:typescriptinterface WithStatic { staticProp: number; // 静态成员 instanceMethod(): void; // 实例成员 } class MyClass implements WithStatic { static staticProp = 42; // 正确,但接口不强制检查 instanceMethod() { /* ... */ } // 必须实现 }
-
泛型接口实现
类需正确传递泛型参数:typescriptinterface GenericInterface<T> { value: T; getValue(): T; } class MyClass<T> implements GenericInterface<T> { constructor(public value: T) {} getValue() { return this.value; } }
-
抽象类实现接口
抽象类可部分实现接口,剩余由子类完成:typescriptabstract class AbstractAnimal implements Animal { constructor(public name: string) {} abstract speak(): void; // 子类必须实现 }
与 extends
的区别
特性 | implements |
extends |
---|---|---|
作用 | 确保类符合接口结构 | 继承父类属性和方法 |
实现方式 | 需手动实现所有成员 | 自动继承父类实现 |
多继承/实现 | 支持多接口(逗号分隔) | 仅单继承(不支持多父类) |
静态成员 | 不检查 | 继承父类静态成员 |
常见问题
-
参数类型兼容性
若接口方法参数为联合类型,实现类需处理所有情况:typescriptinterface MyInterface { func(arg: string | number): void; } class MyClass implements MyInterface { func(arg: string | number) { /* 正确处理所有类型 */ } }
-
构造函数签名
接口无法约束类构造函数,需通过其他模式(如工厂函数)处理。