TypeScript的声明合并是指编译器将对程序中多处出现的同一名字的两个及以上独立声明合并为单一声明,合并后的声明将具有原先所有独立声明的特性。
这是TypeScript中一个非常重要的概念,它允许开发者在不同的地方对同一个实体(如命名空间、类型或值)进行扩展,从而提供了更大的灵活性和代码组织性。
合并接口
接口的合并其实是将两个同名的接口,合并到同一个接口中。
interface Box {
height: number;
width: number;
}
interface Box {
scale: number;
}
let box: Box = {height: 5, width: 6, scale: 10};
如果同名接口中出现同名函数,那么这些函数就会成为一个函数的重载。
interface Box{
getVal(val: number): number
}
interface Box{
getVal(val: string): string
}
// 相当于
interface Box{
getVal(val: number): number
getVal(val: string): string
}
// src/index.ts
const box: Box= {
getVal(val: any) {
return val
}
}
合并命名空间
declare namespace global_type {
interface Box {
name: string
color: string
}
}
declare namespace global_type {
let box: Box
}
// 相当于
declare namespace global_type {
interface Box {
name: string
color: string
}
}
global_type.box = {
name: "",
color: ""
}
合并命名空间和类
class Box {
age: number
}
namespace Box {
export let age: number = 10
}
const box = new Box()
box.age = Box.age
命名空间声明不能位于与之合并的类或函数前