Typescript 类与接口

栏目: 后端 · 发布时间: 6年前

内容简介:通常,一个类只继承另一个类。有时,不同类之间有一些共有的特性,把这些特性提取出来可以提高效率,提取出来的就是接口,用关键字举个例子如下上面报错在于

通常,一个类只继承另一个类。有时,不同类之间有一些共有的特性,把这些特性提取出来可以提高效率,提取出来的就是接口,用关键字 implements 标识。

举个例子如下

  • 手机是一个类;
  • 华为是手机的子类;
  • 拍照是华为手机的一个功能(方法);
  • 数码相机也有拍照功能;
  • 拍照可以抽取出来作为一个接口,华为手机和数码相机都去实现它;
// classInterfaces.ts
// 拍照
interface Photo {
    photo(): string;
}

// 闪光灯
interface Lamp {
    lampOn(): void;
    lampOff(): void;
}

// 手机超类
class Phone {}

// 手机派生类
class HuaweiPhone extends Phone implements Photo, Lamp {
    photo(): string {
        return '华为拍照';
    }
    lampOn() {}
    lampOff(){}
}

// 数码相机
class DigitalCamera implements Photo, Lamp {
    photo(): string {
        console.log('数码拍照')
    }
}

// 0.1.0/classInterfaces.ts:25:7 - error TS2420: Class 'DigitalCamera' incorrectly implements interface 'Lamp'.
    //   Type 'DigitalCamera' is missing the following properties from type 'Lamp': lampOn, lampOff
    // 25 class DigitalCamera implements Photo, Lamp {

// 0.1.0/classInterfaces.ts:26:14 - error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value.
    // 26     photo(): string {
复制代码

上面报错在于

  • DigitalCamera 实现了接口 Lamp ,可却没有定义里面的方法;
  • 接口 Phonephoto 需要返回 string ,可是类 DigitalCamera 中的 phone 没有返回值;

你会发现 一个类可以实现多个接口

接口继承接口

我们知道类可以继承类,其实接口也可以传承接口。

// classInterfaces2.ts
// 闪光灯
interface Lamp {
    lampOn(): void;
    lampOff(): void;
}

// 拍照
interface Photo extends Lamp {
    photo(): string;
}

// 数码相机
class DigitalCamera implements Photo {
    photo(): string {
        return '数码拍照';
    }
    lampOn() {};
    lampOff() {};
}
复制代码

注:类 DigitalCamera 要记得把方法 lampOnlampOff 加上。


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

The Nature of Code

The Nature of Code

Daniel Shiffman / The Nature of Code / 2012-12-13 / GBP 19.95

How can we capture the unpredictable evolutionary and emergent properties of nature in software? How can understanding the mathematical principles behind our physical world help us to create digital w......一起来看看 《The Nature of Code》 这本书的介绍吧!

在线进制转换器
在线进制转换器

各进制数互转换器

随机密码生成器
随机密码生成器

多种字符组合密码

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具