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 加上。


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

查看所有标签

猜你喜欢:

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

Google's PageRank and Beyond

Google's PageRank and Beyond

Amy N. Langville、Carl D. Meyer / Princeton University Press / 2006-7-23 / USD 57.50

Why doesn't your home page appear on the first page of search results, even when you query your own name? How do other web pages always appear at the top? What creates these powerful rankings? And how......一起来看看 《Google's PageRank and Beyond》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具