在 TypeScript 中,implements 关键字用于强制类符合一个或多个接口的结构。

以下是其用法及注意事项的详细介绍:


基本用法

  1. 单个接口实现
    类需实现接口中定义的所有必选属性和方法

    typescript 复制代码
    interface Animal {
      name: string;
      speak(): void;
    }
    
    class Dog implements Animal {
      name: string;  // 必须实现
      constructor(name: string) {
        this.name = name;
      }
      speak() {     // 必须实现
        console.log("Woof!");
      }
    }
  2. 实现多个接口
    用逗号分隔多个接口,类需满足所有接口要求:

    typescript 复制代码
    interface CanRun { run(): void; }
    interface CanSwim { swim(): void; }
    
    class Duck implements CanRun, CanSwim {
      run() { /* ... */ }  // 实现 CanRun
      swim() { /* ... */ } // 实现 CanSwim
    }

注意事项

  1. 严格匹配接口结构

    • 必须实现接口中所有非可选属性和方法,否则编译报错。
    • 方法签名(参数类型、返回值类型、可选性)需一致:
      typescript 复制代码
      interface Greeter {
        greet(name?: string): void;
      }
      
      class EnglishGreeter implements Greeter {
        greet(name?: string) { // 正确:参数可选
          console.log(`Hello, ${name ?? 'Guest'}`);
        }
      }
  2. 可见性一致
    接口成员默认 public,实现时不可改为 privateprotected

    typescript 复制代码
    interface IUser { id: number; }
    
    class User implements IUser {
      private id: number; // 错误:接口要求 public
    }
  3. 可选属性/方法
    可选成员(如 age?: number)在类中可省略,但若实现则需匹配类型。

  4. 静态成员不受检查
    implements 仅检查实例成员,不验证静态成员:

    typescript 复制代码
    interface WithStatic {
      staticProp: number;        // 静态成员
      instanceMethod(): void;    // 实例成员
    }
    
    class MyClass implements WithStatic {
      static staticProp = 42;    // 正确,但接口不强制检查
      instanceMethod() { /* ... */ } // 必须实现
    }
  5. 泛型接口实现
    类需正确传递泛型参数:

    typescript 复制代码
    interface GenericInterface<T> {
      value: T;
      getValue(): T;
    }
    
    class MyClass<T> implements GenericInterface<T> {
      constructor(public value: T) {}
      getValue() { return this.value; }
    }
  6. 抽象类实现接口
    抽象类可部分实现接口,剩余由子类完成:

    typescript 复制代码
    abstract class AbstractAnimal implements Animal {
      constructor(public name: string) {}
      abstract speak(): void; // 子类必须实现
    }

extends 的区别

特性 implements extends
作用 确保类符合接口结构 继承父类属性和方法
实现方式 需手动实现所有成员 自动继承父类实现
多继承/实现 支持多接口(逗号分隔) 仅单继承(不支持多父类)
静态成员 不检查 继承父类静态成员

常见问题

  • 参数类型兼容性
    若接口方法参数为联合类型,实现类需处理所有情况:

    typescript 复制代码
    interface MyInterface {
      func(arg: string | number): void;
    }
    
    class MyClass implements MyInterface {
      func(arg: string | number) { /* 正确处理所有类型 */ }
    }
  • 构造函数签名
    接口无法约束类构造函数,需通过其他模式(如工厂函数)处理。