专业的编程技术博客社区

网站首页 > 博客文章 正文

【TS 七】认识一下ts关键词 implements

baijin 2025-01-31 11:49:24 博客文章 10 ℃ 0 评论

在ts的一些文件里,我们可能会看到一些类的实现里使用到了[implements]这个关键词,可能会有点陌生,今天来学习下

implements

作用

  1. 该关键字用于实现接口(interface)。
  2. 被实现的接口定义了一个对象的形状,包括属性、方法及其类型签名。
  3. 通过使用 implements,类可以声明它遵循某个接口,从而确保类实现了接口中定义的所有属性和方法。

用法

  1. implements关键字用于类声明中,紧随类名之后,后跟要实现的接口名。一个类可以实现多个接口,接口之间用逗号分隔。
  2. 示例
interface Interface1 {
 ...
}
 interface Interface2 {
 ...
}
class MyClass implements Interface1, Interface2 {
    // 类的实现
}



运用场景

  1. 定义对象形状

接口用于定义对象的形状,确保对象具有特定的属性和方法。

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

class MyUser implements User {
    name: string;
    age: number;

    constructor(name: string, age: number) {
        this.name = name;
        this.age = age;
    }

    greet() {
        console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
    }
}

2. 确保类的一致性

通过实现接口,可以确保类遵循特定的结构,从而提高代码的可读性和可维护性。

interface Shape {
    area(): number;
}

class Circle implements Shape {
    radius: number;

    constructor(radius: number) {
        this.radius = radius;
    }

    area() {
        return Math.PI * this.radius * this.radius;
    }
}

class Rectangle implements Shape {
    width: number;
    height: number;

    constructor(width: number, height: number) {
        this.width = width;
        this.height = height;
    }

    area() {
        return this.width * this.height;
    }
}

3. 依赖注入【常用】

接口在依赖注入中非常有用,因为它们允许你定义依赖项的形状,而不依赖于具体的实现。

interface Logger {
    log(message: string): void;
}

class ConsoleLogger implements Logger {
    log(message: string) {
        console.log(message);
    }
}

class FileLogger implements Logger {
    log(message: string) {
        // 写入文件逻辑
    }
}

class MyService {
    private logger: Logger;

    constructor(logger: Logger) {
        this.logger = logger;
    }

    doSomething() {
        this.logger.log('Doing something...');
    }
}


// 创建一个 ConsoleLogger 实例
const consoleLogger = new ConsoleLogger();

// 使用 ConsoleLogger 实例初始化 MyService
const myServiceWithConsoleLogger = new MyService(consoleLogger);

// 调用 MyService 的 doSomething 方法,这将在控制台输出日志
myServiceWithConsoleLogger.doSomething();

// 创建一个 FileLogger 实例
const fileLogger = new FileLogger();

// 使用 FileLogger 实例初始化 MyService
const myServiceWithFileLogger = new MyService(fileLogger);

// 调用 MyService 的 doSomething 方法,这将把日志写入文件
myServiceWithFileLogger.doSomething();


总结

  1. implements 关键字在 TypeScript 中用于实现接口,确保类遵循特定的结构。
  2. 有助于提高代码的可读性、可维护性和可扩展性,特别是在大型项目中。
  3. 通过定义接口,可以清晰地描述对象的形状,并在不同的类之间共享这些定义。

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表