# 宣告合併

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

## 函式的合併

[之前學習過](https://willh.gitbook.io/typescript-tutorial/advanced/pages/-LpS2y9iUNhS7hRqhWhS#過載)，我們可以使用過載定義多個函式型別：

```typescript
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('');
    }
}
```

## 介面的合併

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

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

相當於：

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

注意，**合併的屬性的型別必須是唯一的**：

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

```typescript
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'.
```

介面中方法的合併，與函式的合併一樣：

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

相當於：

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

## 類別的合併

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

同名的類別會發生宣告衝突，無法直接合併。（原文的內容有誤，已發 [Issue](https://github.com/xcatliu/typescript-tutorial/issues/181) 要求更正）

## 參考

* [Declaration Merging](http://www.typescriptlang.org/docs/handbook/declaration-merging.html)（[中文版](https://zhongsp.gitbooks.io/typescript-handbook/content/doc/handbook/Declaration%20Merging.html)）
* [上一章：泛型](/typescript-tutorial/advanced/generics.md)
* [下一章：擴充套件閱讀](/typescript-tutorial/advanced/further-reading.md)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://willh.gitbook.io/typescript-tutorial/advanced/declaration-merging.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
