# 声明合并

WARNING

  • 合并接口
  • 合并命名空间
  • 不同类型合并
    • 命名空间和函数
    • 命名空间和枚举

ts 会将多个名字相同的声明合并为一个声明。合并后的声明同时具备多个声明的特性。

interface Info {
	name: string
}

interface Info {
	age: number
}

let info: Info

info = {
	name: 'xiaoyu',
	age: 19
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14

静态图片

对于接口里的函数成员,每个同名函数成员都会被当做函数的重载并且合并之后后面的接口具有更高的优先级。


interface Info {
	name: string,
	getRes(input: string): number
}

interface Info {
	age: number,
	getRes(input: number): string
}

let info: Info

info = {
	name: 'xiaoyu',
	age: 19,
    // 函数重载
	getRes(text: any): any {
		if (typeof text === 'string') {
			return text.length
		} else {
			return String(text)
		}
	}
}

console.log(info.getRes(123))
console.log(info.getRes('哈哈哈'))

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
namespace Validations {
  const number = 12
  export const checkNumber = () => {}
}

namespace Validations {
  // console.log(number) // 获取不到,除非导出number
  export const checkLetter = () => {}
}

/***************************/
// 相当于定义了一个命名空间里面有两个方法
namespace Validations {
  export const checkNumber = () => {}
  export const checkLetter = () => {}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

不同类型的合并

  • 同名的类要定义在同名的命名空间前面
class Validations {
	constructor() {
	}
	checkType () {}
}

namespace Validations {
	export const checkNumber = () => {}
}

console.dir(Validations)
1
2
3
4
5
6
7
8
9
10
11

静态图片

函数和命名空间,函数要放到前面


function countUp () {
	countUp.count++
}

namespace countUp {
	export let count = 0
}
console.log(countUp.count) // 0
countUp()
console.log(countUp.count) // 1

1
2
3
4
5
6
7
8
9
10
11
12

命名空间和枚举的合并(没有顺序要求)

enum Colors {
	red,
	green,
	blue
}

namespace Colors {
	export const yellow =3
}

console.log(Colors, 'colors')

1
2
3
4
5
6
7
8
9
10
11
12

静态图片