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 屬性」。看著有點笨重,而 myObj 實際上同時有 size 與 label 兩個屬性,只是函式只關心 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,編譯階段就會直接報錯。

方法型別

在 JavaScript 中,函式本身就是一種基本型別。既然物件導向裡介面靠類別實作,那麼函式能不能實作介面?答案是可以的——我們可以用介面約束函式的簽章。

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

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

需要注意的是,編譯器只檢查型別是否吻合(參數型別與回傳型別),因此參數名稱完全可以換掉:

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

這樣寫一樣能通過編譯。

陣列型別

介面裡既然能描述函式,自然也能描述陣列,寫法同樣直觀:

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

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

這代表 myArray 是一個索引為 number、元素為 string 的陣列。索引器的名稱慣例上寫作 index,但改成別的名字也沒問題:

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

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

但要記住:索引器的型別只能是 number 或 string。

interface Array {
  [index: number]: any;
}

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

最後還有一個容易忽略的規則:一旦介面被定義為陣列型別,介面中其他屬性的型別都必須是該陣列元素的型別(或其子型別)。例如:

interface Dictionary {
  [index: string]: string;
  length: number; // error, the type of 'length' is not a subtype of the indexer
}

這段就無法通過編譯,必須把 length 也改成 string 才行。

用類別實作介面

實務上我們更習慣用類別來實作介面,而不是到處直接寫介面型別:

interface ClockInterface {
  currentTime: Date;
}

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

class 關鍵字與 ECMAScript 6 一致。介面同樣可以用來約束類別中定義的方法:

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);
}

接下來你可能會很自然地寫出這樣的程式:

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

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

這是不行的!因為建構函式屬於靜態(static)層面,而類別只能實作介面中的實例(instance)部分。

那這個簽章豈不是沒用?当然不是。它的正確用法是把類別本身指派給該型別的變數:

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);

正常情況下我們會直接寫 new Clock,這裡則是把 Clock 類別指向 ClockStatic 介面。要注意的是,newClock 的型別是 any。

介面的繼承

和類別一樣,介面透過 extends 關鍵字也能繼承:

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;

這裡一口氣用到了三種形式:介面本身是個可呼叫的方法、一個 interval 屬性,以及一個 reset 方法成員。

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