前面章節 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 { 複製代碼
上面報錯在於markdown
DigitalCamera
實現了接口 Lamp
,可卻沒有定義裏面的方法;Phone
中 photo
須要返回 string
,但是類 DigitalCamera
中的 phone
沒有返回值;總結(發現)函數
HuaweiPhone
中 lampOff
和 lampOn
並無按照接口 Lamp
按順序定義,這說明類型檢查器不會檢查屬性或方法的順序,只要有相應的屬性或方法且類型也是對的就能夠了;咱們知道類能夠繼承類,其實接口也能夠傳承接口。這種方式能夠靈活地將接口分割到可重用的模塊裏。oop
// 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 拍照就是酷兒 複製代碼
你還會發現:一個接口能夠繼承多個接口,建立出多個接口的合成接口。post
注:類
DigitalCamera
要記得把方法lampOn
、lampOff
、photo
和showWxNumber
加上。ui
咱們看過類實現接口,接口繼承接口,那接口能繼承類嗎?this
// 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(); 複製代碼