DIV CSS 佈局教程網

TypeScript 介面詳解:從物件契約到類別實作
編輯:JavaScript綜合知識     

TypeScript 的核心設計原則之一是型別檢查,而介面(interface)正是執行這件事的主要工具。它符合傳統物件導向的思想,能有效避免型別轉換上的問題。要特別注意的是,介面只用於編譯期的約束,編譯成 JavaScript 時所有介面都會被擦除,因為 JavaScript 本身並沒有這個概念。

從物件字面量型別開始

function printLabel(labelledObj: { label: string }) {
  console.log(labelledObj.label);
}

var myObj = { size: 10, label: "Size 10 Object" };
printLabel(myObj);

參數 labelledObj 的型別是 { label: string },意思是它必須具備一個字串型的 label 屬性。這種寫法可讀性不佳,這時就可以用介面替它命名:

interface LabelledValue {
  label: string;
}

function printLabel(labelledObj: LabelledValue) {
  console.log(labelledObj.label);
}

var myObj = { size: 10, label: "Size 10 Object" };
printLabel(myObj);

可選屬性

有些屬性並非必要,這時在名稱後加上問號即可:

interface SquareConfig {
  color?: string;
  width?: number;
}

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

var mySquare = createSquare({ color: "black" });

既然可有可無,為什麼還要宣告?有兩個理由:一是屬性存在時仍能約束型別,二是能得到語法提示——若把 color 誤寫成 collor,編譯不會通過。

方法型別

函數也能用介面約束,寫法是在介面中描述它的簽名:

interface SearchFunc {
  (source: string, subString: string): boolean;
}

var mySearch: SearchFunc;
mySearch = function(source: string, subString: string) {
  var result = source.search(subString);
  return result != -1;
}

編譯器只檢查參數型別與回傳型別,參數的名稱可以自由更換:

var mySearch: SearchFunc;
mySearch = function(src: string, sub: string) {
  return src.search(sub) != -1;
}

陣列型別與索引簽名

interface StringArray {
  [index: number]: string;
}

var myArray: StringArray;
myArray = ["Bob", "Fred"];

這代表 myArray 是一個索引為 number、元素為 string 的陣列。索引器的名稱慣例是 index,但改成別的名字(例如 [myIndex: number])也能通過編譯。索引器型別只能是 number 或 string:

interface ArrayLike { [index: number]: any; }
interface Dictionary { [index: string]: any; }

還有一個限制:若介面已是陣列型別,介面中其他屬性的型別都必須是該陣列的元素型別。

interface Dictionary {
  [index: string]: string;
  length: number;   // 錯誤:length 的型別不是索引器的子型別
}

必須把 length 也改成 string 才能通過。

用類別實作介面

interface ClockInterface {
  currentTime: Date;
}

class Clock implements ClockInterface {
  currentTime: Date;
  constructor(h: number, m: number) { }
}

介面也能約束類別中的方法:

interface ClockInterface {
  currentTime: Date;
  setTime(d: Date);
}

class Clock implements ClockInterface {
  currentTime: Date;
  setTime(d: Date) { this.currentTime = d; }
  constructor(h: number, m: number) { }
}

建構函數簽名的陷阱

TypeScript 允許在介面中描述建構函數:

interface ClockInterface {
  new (hour: number, minute: number);
}

直覺地接著寫 class Clock implements ClockInterface 是行不通的,因為建構函數屬於靜態(static)部分,而類別只能實作介面中的實例部分。正確用法是把類別本身指派給該型別:

interface ClockStatic {
  new (hour: number, minute: number);
}

class Clock {
  currentTime: Date;
  constructor(h: number, m: number) { }
}

var cs: ClockStatic = Clock;
var newClock = new cs(7, 30);

注意 newClock 的型別會是 any。

介面繼承

interface Shape { color: string; }
interface Square extends Shape { sideLength: number; }

var square = <Square>{};
square.color = "blue";
square.sideLength = 10;

也可以繼承多個介面:

interface Shape { color: string; }
interface PenStroke { penWidth: number; }
interface Square extends Shape, PenStroke { sideLength: number; }

var square = <Square>{};
square.color = "blue";
square.sideLength = 10;
square.penWidth = 5.0;

但若被繼承的介面中存在同名屬性而型別不同,編譯不會通過:

interface Shape { color: string; test: number; }
interface PenStroke { penWidth: number; test: string; }
interface Square extends Shape, PenStroke { sideLength: number; }
// 錯誤:test 的型別無法確定

多種類型同時使用

interface Counter {
  (start: number): string;
  interval: number;
  reset(): void;
}

var c: Counter;
c(10);
c.reset();
c.interval = 5.0;

這裡同時用到了三種描述:呼叫簽名(介面本身是個可呼叫的函數)、屬性、以及方法成員。

最後提醒一個觀念:介面在 TypeScript 中是「結構化型別」的,也就是說只要形狀符合就算實作,不需要明確宣告 implements。這與 Java、C# 那種必須明示的 nominal typing 不同,也是為什麼前面 printLabel(myObj) 能直接通過——myObj 從未宣告自己實作了 LabelledValue,但它的形狀符合。

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