DIV CSS 佈局教程網

TypeScript 入門教程:深入認識接口
編輯:JavaScript技巧     

在 TypeScript 中,接口的核心作用是為類型命名,並為你的代碼或第三方代碼定義清晰的契約。下面我們從基礎示例出發,逐一梳理接口的常見用法。

基礎接口

先看一個未使用接口的例子:

 function printLabel(labelledObj: { label: string }) { console.log(labelledObj.label); } let myObj = { size: 10, label: "Size 10 Object" }; printLabel(myObj); 

這裡的 printLabel 函數要求傳入的參數是一個物件,且必須帶有名為 label、類型為 string 的屬性。當參數較多、但我們只想約束其中一部分時,接口就能派上用場:

 interface LabelledValue { label: string; } function printLabel(labelledObj: LabelledValue) { console.log(labelledObj.label); } let myObj = {size: 10, label: "Size 10 Object"}; printLabel(myObj);

關鍵在於使用 interface 關鍵字來聲明接口。

可選屬性

並非所有屬性都是必須的。若某個屬性可有可無,只需在名稱後加上問號 ?:

 interface SquareConfig { color?: string; width?: number; } function createSquare(config: SquareConfig): {color: string; area: number} { let newSquare = {color: "white", area: 100}; if (config.color) { newSquare.color = config.color; } if (config.width) { newSquare.area = config.width * config.width; } return newSquare; } let mySquare = createSquare({color: "black"});

上述代碼中,config: SquareConfig 規定了參數類型,而 {color: string; area: number} 則規定了回傳值的結構。使用可選屬性的好處有兩點:一是能靈活描述可能存在的屬性,二是能在訪問不存在的屬性時及時捕獲錯誤。

只讀屬性

若希望某個屬性一經定義便不可修改,可以使用 readonly:

 interface Point { readonly x: number; readonly y: number; } let p1: Point = { x: 10, y: 20 }; p1.x = 5; // error!

TypeScript 還提供了 ReadonlyArray<T> 類型,它與 Array<T> 相似,只是移除了所有可變方法,能確保陣列建立後不再被改動:

 let a: number[] = [1, 2, 3, 4]; let ro: ReadonlyArray<number> = a; ro[0] = 12; // error! ro.push(5); // error! ro.length = 100; // error! a = ro; // error! 

額外的屬性檢查

再看一個例子:

 interface SquareConfig { color?: string; width?: number; } function createSquare(config: SquareConfig): { color: string; area: number } { // ... } let mySquare = createSquare({ colour: "red", width: 100 });

乍看之下這段代碼似乎沒問題——接口定義了 color 與 width 兩個可選屬性,傳入的物件卻多了一個未定義的 colour,於是便會報錯。原因是:物件字面量會被特殊對待並進行「額外屬性檢查」,一旦它含有目標類型未包含的屬性,就會拋出錯誤。最簡單的解法,是添加一個字串索引簽名:

 interface SquareConfig { color?: string; width?: number; [propName: string]: any; }

函數類型

接口同樣可以用來描述函數的結構:

 interface SearchFunc { (source: string, subString: string): boolean; } let mySearch: SearchFunc; mySearch = function(src, sub) { let result = src.search(sub); if (result == -1) { return false; } else { return true; } }

可索引的類型

諸如 a[10] 或 obj['a'] 這樣的寫法即為可索引類型。它擁有索引簽名,用於描述索引的類型以及對應的回傳值類型:

 interface StringArray { [index: number]: string; } let myArray: StringArray; myArray = ["Bob", "Fred"]; let myStr: string = myArray[0];

以上就是 TypeScript 接口的常見用法梳理,希望能幫助你更扎實地掌握這一核心概念。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved