前面章节 Typescript 对象类型-接口,主要讲接口对对象属性的类型描述。git
本章说道另外一做用,能够说当对象遇到接口,给你不同的精彩。github
一般,一个类只继承另外一个类。有时,不一样类之间有一些共有的特性,把这些特性提取出来能够提升效率,提取出来的就是接口,用关键字 implements
标识。typescript
举个例子以下微信
// classInterfaces.ts
// 拍照
interface Photo {
photo(): string;
}
// 闪光灯
interface Lamp {
lampOn(): void;
lampOff(): void;
}
// 手机超类
class Phone {}
// 手机派生类
class HuaweiPhone extends Phone implements Photo, Lamp {
photo(): string {
return '华为拍照';
}
lampOff() {}
lampOn(){}
}
// 数码相机
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
,可却没有定义里面的方法;Phone
中 photo
须要返回 string
,但是类 DigitalCamera
中的 phone
没有返回值;总结(发现)post
HuaweiPhone
中 lampOff
和 lampOn
并无按照接口 Lamp
按顺序定义,这说明类型检查器不会检查属性或方法的顺序,只要有相应的属性或方法且类型也是对的就能够了;咱们知道类能够继承类,其实接口也能够传承接口。这种方式能够灵活地将接口分割到可重用的模块里。ui
// classInterfaces2.ts
interface Lamp {
lampOn(): void;
lampOff(): void;
}
interface wx {
wxNumber: number;
showWxNumber(): string;
}
// 拍照
interface Photo extends Lamp, Tel {
photo(): string;
}
// 华为手机
class HuaweiPhone2 implements Photo {
public wxNumber: number;
photo(): string {
return '华为手机 mate20 pro 拍照就是酷儿';
}
lampOn() {};
lampOff() {};
constructor(wxNumber: number) {
this.wxNumber = wxNumber;
};
showWxNumber(){
return `个人微信号:liferzy`;
}
}
let huaweiPhone = new HuaweiPhone2(13701833766);
console.log(huaweiPhone.showWxNumber()); // 个人微信号:liferzy
console.log(huaweiPhone.photo()); // 华为手机 mate20 pro 拍照就是酷儿
复制代码
你还会发现:一个接口能够继承多个接口,建立出多个接口的合成接口。this
注:类
DigitalCamera
要记得把方法lampOn
、lampOff
、photo
和showWxNumber
加上。es5
咱们看过类实现接口,接口继承接口,那接口能继承类吗?spa
// classInterfaces3.ts
class Xy {
x: number;
y: number;
}
interface Xyz extends Xy {
z: number;
}
let xyz: Xyz = { x: 1, y: 2, z: 3 };
复制代码
在 Typescript 函数类型 文章中,函数类型表示的招式之一就是接口,其例子是
// function5.ts
interface Function5 {
(x: string, y: string): boolean
}
let function5: Function5 = (x: string, y: string) => {
return x.search(y) > -1;
}
复制代码
这里补充下:对于函数类型的类型检查,函数的参数名能够不与接口里定义的参数名一致,好比
// function5_2.ts
interface Function5_2 {
(x: string, y: string): boolean
}
let function5_2: Function5_2 = (name: string, firstName: string) => {
return name.search(firstName) > -1;
}
console.log(function5_2('pr is a boy', 'pr')); // true
复制代码
接口牛逼之处能够描述 JavaScript 里丰富的类型。需求场景有时须要一个对象能够同时具备多种类型。
// classInterfaces5.ts
interface Counter {
(start: number): string;
interval: number;
reset(): void;
}
function getCounter(): Counter {
const counter = <Counter>function(start: number) {};
counter.interval = 1;
counter.reset = () => {};
return counter;
}
let c = getCounter();
c(1);
c.interval = 2;
c.reset();
复制代码