TypeScript接口实现 #

一、接口实现基础 #

1.1 implements关键字 #

使用implements关键字让类实现接口:

typescript
interface Printable {
    print(): void;
}

class Document implements Printable {
    print(): void {
        console.log('Printing document...');
    }
}

const doc = new Document();
doc.print();

1.2 接口定义规范 #

接口定义了类必须实现的成员:

typescript
interface User {
    name: string;
    age: number;
    greet(): string;
}

class Person implements User {
    name: string;
    age: number;
    
    constructor(name: string, age: number) {
        this.name = name;
        this.age = age;
    }
    
    greet(): string {
        return `Hello, I'm ${this.name}`;
    }
}

二、实现多个接口 #

2.1 多接口实现 #

typescript
interface Printable {
    print(): void;
}

interface Serializable {
    serialize(): string;
}

class Document implements Printable, Serializable {
    print(): void {
        console.log('Printing...');
    }
    
    serialize(): string {
        return 'Document content';
    }
}

2.2 接口组合 #

typescript
interface Loggable {
    log(message: string): void;
}

interface Storable {
    save(): void;
}

interface Loadable {
    load(): void;
}

class DataManager implements Loggable, Storable, Loadable {
    log(message: string): void {
        console.log(message);
    }
    
    save(): void {
        this.log('Saving data...');
    }
    
    load(): void {
        this.log('Loading data...');
    }
}

2.3 接口冲突处理 #

typescript
interface A {
    method(): void;
}

interface B {
    method(): void;
}

class C implements A, B {
    method(): void {
        console.log('Implementing method');
    }
}

三、接口继承类 #

3.1 接口继承类 #

接口可以继承类,获取类的成员但不包含实现:

typescript
class Control {
    private state: any;
    
    public enable(): void {}
    public disable(): void {}
}

interface SelectableControl extends Control {
    select(): void;
}

class Button extends Control implements SelectableControl {
    select(): void {
        console.log('Button selected');
    }
}

3.2 继承私有成员 #

typescript
class Base {
    private secret: string = 'secret';
}

interface Derived extends Base {
    method(): void;
}

class Implementation extends Base implements Derived {
    method(): void {
        console.log(this.secret);
    }
}

四、类类型 #

4.1 类作为类型 #

typescript
class User {
    constructor(public name: string) {}
    
    greet(): string {
        return `Hello, ${this.name}`;
    }
}

const user: User = new User('Alice');

function process(user: User): void {
    console.log(user.greet());
}

4.2 构造签名 #

typescript
interface AnimalConstructor {
    new (name: string): Animal;
}

interface Animal {
    name: string;
    move(): void;
}

class Dog implements Animal {
    constructor(public name: string) {}
    
    move(): void {
        console.log(`${this.name} is moving`);
    }
}

function createAnimal(ctor: AnimalConstructor, name: string): Animal {
    return new ctor(name);
}

const dog = createAnimal(Dog, 'Max');

4.3 抽象构造签名 #

typescript
interface AbstractConstructor<T> {
    new (...args: any[]): T;
}

abstract class Base {
    abstract method(): void;
}

class Derived extends Base {
    method(): void {
        console.log('Method implementation');
    }
}

function create<T>(ctor: AbstractConstructor<T>, ...args: any[]): T {
    return new ctor(...args);
}

五、接口与抽象类 #

5.1 接口实现vs抽象类继承 #

typescript
interface Printable {
    print(): void;
}

abstract class Document {
    abstract print(): void;
    
    save(): void {
        console.log('Saving...');
    }
}

class TextDocument extends Document implements Printable {
    print(): void {
        console.log('Printing text...');
    }
}

5.2 结合使用 #

typescript
interface Serializable {
    serialize(): string;
}

interface Cloneable {
    clone(): this;
}

abstract class Entity {
    constructor(public id: number) {}
    
    abstract describe(): string;
}

class User extends Entity implements Serializable, Cloneable {
    constructor(
        id: number,
        public name: string,
        public email: string
    ) {
        super(id);
    }
    
    describe(): string {
        return `User: ${this.name}`;
    }
    
    serialize(): string {
        return JSON.stringify({ id: this.id, name: this.name, email: this.email });
    }
    
    clone(): this {
        return Object.create(this);
    }
}

六、泛型接口实现 #

6.1 泛型接口 #

typescript
interface Repository<T> {
    findById(id: number): Promise<T | null>;
    findAll(): Promise<T[]>;
    save(entity: T): Promise<T>;
    delete(id: number): Promise<void>;
}

class UserRepository implements Repository<User> {
    async findById(id: number): Promise<User | null> {
        return null;
    }
    
    async findAll(): Promise<User[]> {
        return [];
    }
    
    async save(entity: User): Promise<User> {
        return entity;
    }
    
    async delete(id: number): Promise<void> {}
}

6.2 泛型类实现泛型接口 #

typescript
interface Container<T> {
    get(): T;
    set(value: T): void;
}

class Box<T> implements Container<T> {
    private value: T;
    
    constructor(value: T) {
        this.value = value;
    }
    
    get(): T {
        return this.value;
    }
    
    set(value: T): void {
        this.value = value;
    }
}

七、实用示例 #

7.1 事件系统 #

typescript
interface EventListener<T = any> {
    (event: T): void;
}

interface EventEmitter<T = any> {
    on(event: string, listener: EventListener<T>): void;
    off(event: string, listener: EventListener<T>): void;
    emit(event: string, data: T): void;
}

class SimpleEventEmitter<T = any> implements EventEmitter<T> {
    private listeners: Map<string, EventListener<T>[]> = new Map();
    
    on(event: string, listener: EventListener<T>): void {
        if (!this.listeners.has(event)) {
            this.listeners.set(event, []);
        }
        this.listeners.get(event)!.push(listener);
    }
    
    off(event: string, listener: EventListener<T>): void {
        const listeners = this.listeners.get(event);
        if (listeners) {
            const index = listeners.indexOf(listener);
            if (index !== -1) {
                listeners.splice(index, 1);
            }
        }
    }
    
    emit(event: string, data: T): void {
        const listeners = this.listeners.get(event);
        if (listeners) {
            listeners.forEach(listener => listener(data));
        }
    }
}

7.2 插件系统 #

typescript
interface Plugin {
    name: string;
    version: string;
    install(app: Application): void;
    uninstall?(app: Application): void;
}

interface Application {
    plugins: Plugin[];
    use(plugin: Plugin): void;
}

class MyApp implements Application {
    plugins: Plugin[] = [];
    
    use(plugin: Plugin): void {
        this.plugins.push(plugin);
        plugin.install(this);
    }
}

const loggerPlugin: Plugin = {
    name: 'logger',
    version: '1.0.0',
    install(app: Application) {
        console.log('Logger plugin installed');
    }
};

const app = new MyApp();
app.use(loggerPlugin);

7.3 策略模式 #

typescript
interface SortStrategy {
    sort(data: number[]): number[];
}

class BubbleSort implements SortStrategy {
    sort(data: number[]): number[] {
        console.log('Using bubble sort');
        return [...data].sort((a, b) => a - b);
    }
}

class QuickSort implements SortStrategy {
    sort(data: number[]): number[] {
        console.log('Using quick sort');
        return [...data].sort((a, b) => a - b);
    }
}

class Sorter {
    constructor(private strategy: SortStrategy) {}
    
    setStrategy(strategy: SortStrategy): void {
        this.strategy = strategy;
    }
    
    sort(data: number[]): number[] {
        return this.strategy.sort(data);
    }
}

八、最佳实践 #

8.1 接口命名约定 #

typescript
interface IUserService {}
interface IValidator {}
interface ILogger {}

或使用更现代的命名:

typescript
interface UserService {}
interface Validator {}
interface Logger {}

8.2 接口分离原则 #

typescript
interface UserReader {
    findById(id: number): Promise<User | null>;
    findAll(): Promise<User[]>;
}

interface UserWriter {
    save(user: User): Promise<User>;
    delete(id: number): Promise<void>;
}

interface UserRepository extends UserReader, UserWriter {}

8.3 使用接口定义契约 #

typescript
interface Cache {
    get<T>(key: string): Promise<T | null>;
    set<T>(key: string, value: T, ttl?: number): Promise<void>;
    delete(key: string): Promise<void>;
}

class MemoryCache implements Cache {
    private cache: Map<string, { value: any; expires: number }> = new Map();
    
    async get<T>(key: string): Promise<T | null> {
        const item = this.cache.get(key);
        if (!item || Date.now() > item.expires) {
            return null;
        }
        return item.value;
    }
    
    async set<T>(key: string, value: T, ttl: number = 3600000): Promise<void> {
        this.cache.set(key, { value, expires: Date.now() + ttl });
    }
    
    async delete(key: string): Promise<void> {
        this.cache.delete(key);
    }
}

九、总结 #

本章介绍了TypeScript接口实现:

接口实现要点 #

  1. 使用implements关键字实现接口
  2. 可以实现多个接口
  3. 接口可以继承类
  4. 类必须实现接口的所有成员

接口vs抽象类 #

  • 接口:定义契约,多实现
  • 抽象类:提供实现,单继承

最佳实践 #

  1. 使用接口定义契约
  2. 遵循接口分离原则
  3. 合理组合接口和抽象类
  4. 使用泛型接口提高复用性
最后更新:2026-03-26