# 聲明合并
如果定義了兩個相同名字的函數、接口或類,那么它們會合并成一個類型:
## 函數的合并
[之前學習過](../basics/type-of-function.md#重載),我們可以使用重載定義多個函數類型:
```ts
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('');
}
}
```
## 接口的合并
接口中的屬性在合并時會簡單的合并到一個接口中:
```ts
interface Alarm {
price: number;
}
interface Alarm {
weight: number;
}
```
相當于:
```ts
interface Alarm {
price: number;
weight: number;
}
```
注意,**合并的屬性的類型必須是唯一的**:
```ts
interface Alarm {
price: number;
}
interface Alarm {
price: number; // 雖然重復了,但是類型都是 `number`,所以不會報錯
weight: number;
}
```
```ts
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'.
```
接口中方法的合并,與函數的合并一樣:
```ts
interface Alarm {
price: number;
alert(s: string): string;
}
interface Alarm {
weight: number;
alert(s: string, n: number): string;
}
```
相當于:
```ts
interface Alarm {
price: number;
weight: number;
alert(s: string): string;
alert(s: string, n: number): string;
}
```
## 類的合并
類的合并與接口的合并規則一致。
## 參考
- [Declaration Merging](http://www.typescriptlang.org/docs/handbook/declaration-merging.html)([中文版](https://zhongsp.gitbooks.io/typescript-handbook/content/doc/handbook/Declaration%20Merging.html))
---
- [上一章:泛型](generics.md)
- [下一章:擴展閱讀](further-reading.md)