TypeScript 新手指南
  • 前言
  • 簡介
    • 什麼是 TypeScript
    • 安裝 TypeScript
    • Hello TypeScript
  • 基礎
    • 原始資料型別
    • 任意值
    • 型別推論
    • 聯合型別
    • 物件的型別——介面
    • 陣列的型別
    • 函式的型別
    • 型別斷言
    • 宣告檔案
    • 內建物件
  • 進階
    • 型別別名
    • 字串字面量型別
    • 元組
    • 列舉
    • 類別
    • 類別與介面
    • 泛型
    • 宣告合併
    • 延伸閱讀
  • 工程
    • 程式碼檢查
  • 感謝
Powered by GitBook
On this page
  • 函式的合併
  • 介面的合併
  • 類別的合併
  • 參考

Was this helpful?

  1. 進階

宣告合併

Previous泛型Next延伸閱讀

Last updated 4 years ago

Was this helpful?

如果定義了兩個相同名字的函式、介面或類別,那麼它們會合併成一個型別:

函式的合併

,我們可以使用過載定義多個函式型別:

function reverse(x: number): number;
function reverse(x: string): string;
function reverse(x: number | string): number | string {
    if (typeof x === 'number') {
        return Number(x.toString().split('').reverse().join(''));
    } else if (typeof x === 'string') {
        return x.split('').reverse().join('');
    }
}

介面的合併

介面中的屬性在合併時會簡單的合併到一個介面中:

interface Alarm {
    price: number;
}
interface Alarm {
    weight: number;
}

相當於:

interface Alarm {
    price: number;
    weight: number;
}

注意,合併的屬性的型別必須是唯一的:

interface Alarm {
    price: number;
}
interface Alarm {
    price: number;  // 雖然重複了,但是型別都是 `number`,所以不會報錯
    weight: number;
}
interface Alarm {
    price: number;
}
interface Alarm {
    price: string;  // 型別不一致,會報錯
    weight: number;
}

// index.ts(5,3): error TS2403: Subsequent variable declarations must have the same type.  Variable 'price' must be of type 'number', but here has type 'string'.

介面中方法的合併,與函式的合併一樣:

interface Alarm {
    price: number;
    alert(s: string): string;
}
interface Alarm {
    weight: number;
    alert(s: string, n: number): string;
}

相當於:

interface Alarm {
    price: number;
    weight: number;
    alert(s: string): string;
    alert(s: string, n: number): string;
}

類別的合併

類別的合併與介面的合併規則一致。

參考

同名的類別會發生宣告衝突,無法直接合併。(原文的內容有誤,已發 要求更正)

()

Issue
Declaration Merging
中文版
上一章:泛型
下一章:擴充套件閱讀
之前學習過