TypeScript从精通到入门11:声明合并

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

命名空间声明不能位于与之合并的类或函数前

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值