萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

TypeScript 介面 完整指南:約束物件結構、函式簽名、陣列索引與類別實現

介面 是 TypeScript 核心類型系統的基石,用於定義物件形狀契約、函式簽名、陣列/字典索引類型,並在編譯期提供強型別檢查與智能提示。編譯為 JavaScript 時介面完全擦除,零運行時開銷。本文全面解析介面語法、進階特性與實戰模式。

基本物件結構約束

// 內聯型別標註 (簡單場景)
function printLabel(obj: { label: string }) {
  console.log(obj.label);
}
printLabel({ size: 10, label: "Size 10" }); // 多餘屬性被允許 (鴨子類型)

// 介面提取複用 (推薦)
interface LabelledValue {
  label: string;
}
function printLabel(obj: LabelledValue) {
  console.log(obj.label);
}
printLabel({ size: 10, label: "Size 10" }); // 通過

可選屬性

屬性名後加 ? 表示可選,兼具「存在時檢查型別」與「智能提示」雙重優勢。

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" }); // width 可選
// createSquare({ colour: "red" }); // 錯誤:拼寫錯誤被攔截

唯讀屬性

interface Point {
  readonly x: number;
  readonly y: number;
}
let p1: Point = { x: 10, y: 20 };
// p1.x = 5; // 錯誤:唯讀屬性不可修改

// ReadonlyArray 陣列唯讀
let a: number[] = [1, 2, 3];
let ro: ReadonlyArray = a;
// ro[0] = 12; // 錯誤
// ro.push(5); // 錯誤
// a = ro;     // 錯誤:唯讀不可賦值給可變
// a = ro as number[]; // 強制斷言 (慎用)

函式類型介面

介面可描述函式簽名:參數類型、返回類型。參數名稱僅供文檔用,不強制一致。

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

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

可索引類型 (陣列/字典)

定義索引簽名:[index: 索引類型]: 值類型。索引類型僅支援 string 或 number。

// 陣列類型
interface StringArray {
  [index: number]: string;
}
let myArray: StringArray = ["Bob", "Fred"];
let second = myArray[1]; // string

// 字典類型
interface StringMap {
  [key: string]: string;
}
let map: StringMap = { key1: "value1" };
map["key2"] = "value2";

// 索引簽名強制所有屬性符合值類型
interface NumberMap {
  [key: string]: number;
  length: number;    // 合法:number
  // name: string;    // 錯誤:string 不符合 number
}

介面繼承與混合

interface Shape { color: string; }
interface PenStroke { penWidth: number; }

// 多重繼承
interface Square extends Shape, PenStroke {
  sideLength: number;
}
let square: Square = { color: "blue", penWidth: 5, sideLength: 10 };

// 混合類型:既是函式又有屬性
interface Counter {
  (start: number): string; // 呼叫簽名
  interval: number;        // 屬性
  reset(): void;           // 方法
}
function getCounter(): Counter {
  let counter = function(start: number) { return String(start); };
  counter.interval = 123;
  counter.reset = function() { };
  return counter;
}
let c = getCounter();
c(10);        // "10"
c.interval;   // 123
c.reset();    // void

類別實現介面

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

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

// 介面僅約束公開面,不約束私有/建構子
interface ClockConstructor {
  new (hour: number, minute: number): ClockInterface;
}
function createClock(ctor: ClockConstructor, hour: number, minute: number): ClockInterface {
  return new ctor(hour, minute);
}

介面 vs 類型別名

特性interfacetype
物件/函式/類別約束✅ 原生支援✅ 支援
基本型別別名❌✅ type ID = string | number
聯集/交集型別❌✅ type A = B & C
元組/陣列簡寫❌✅ type Pair = [string, number]
聲明合併✅ 同名介面自動合併❌ 重複聲明報錯
類別 implements✅✅ (需滿足結構)

原則:定義物件/函式/類別契約用 interface (利於擴展合併);聯集/交集/基本型別別名/元組用 type。

聲明合併

interface Box { height: number; width: number; }
interface Box { scale: number; } // 自動合併
let box: Box = { height: 10, width: 20, scale: 1.5 };

常用於第三方庫類型擴充 (如 declare module 'express' { interface Request { user?: User } })。

實戰最佳實踐

  1. 領域模型優先定義介面:interface User、interface Order 放在 types/ 或 models/ 目錄。
  2. API 回應型別:後端 Swagger/OpenAPI 生成 TS 介面,前端直接引用,端到端類型安全。
  3. Props 介面:React/Vue 組件 Props 定義為介面,獲得完整 IDE 提示。
  4. 避免過度設計:內部實現細節用 type 或類別私有欄位,介面僅暴露公開契約。
  5. 啟用嚴格模式:strict: true 確保介面約束真正生效。

介面是 TypeScript 靜態類型系統的「契約語言」,善用介面定義邊界、文檔化假設、啟用編譯期守護,是構建大型可維護應用的關鍵基礎設施。

copyright © 萬盛學電腦網 all rights reserved