当前位置: 首页 > news >正文

TypeScript声明合并详解二

接上篇文章

命名空间与类/函数/枚举合并

命名空间可以与其他类型的声明合并:

与类合并

class Person {constructor(public name: string) {}
}namespace Person {export function createAnonymous() {return new Person("Anonymous");}
}const person1 = new Person("Alice");
const person2 = Person.createAnonymous();

与函数合并

function buildName(firstName: string, lastName?: string) {// ...
}namespace buildName {export interface Options {firstName: string;lastName?: string;}export function fromOptions(options: Options) {return buildName(options.firstName, options.lastName);}
}buildName("John", "Doe");
buildName.fromOptions({ firstName: "Jane" });

与枚举合并

enum Color {Red = 1,Green = 2,Blue = 4
}namespace Color {export function mix(color1: Color, color2: Color) {return color1 | color2;}
}const yellow = Color.mix(Color.Red, Color.Green);

合并顺序规则

合并的顺序会影响最终结果:

  1. 接口内部的声明按书写顺序合并

  2. 后面的接口具有更高优先级

  3. 对于函数重载,后面的接口出现在更前面

interface Cloner {clone(animal: Animal): Animal;
}interface Cloner {clone(animal: Sheep): Sheep;
}interface Cloner {clone(animal: Dog): Dog;clone(animal: Cat): Cat;
}// 合并后的顺序:
// clone(animal: Dog): Dog;
// clone(animal: Cat): Cat;
// clone(animal: Sheep): Sheep;
// clone(animal: Animal): Animal;

实际应用场景

1. 扩展第三方库类型

// 扩展 express 的 Request 类型
declare namespace Express {export interface Request {user?: {id: string;name: string;};}
}

2. 为现有类添加静态方法

class Calculator {static add(a: number, b: number): number {return a + b;}
}namespace Calculator {export function multiply(a: number, b: number): number {return a * b;}
}

3. 模块增强

// user.ts
export interface User {id: string;name: string;
}// user-extension.ts
import { User } from './user';declare module './user' {interface User {email?: string;age?: number;}
}// 现在 User 接口包含了扩展的属性

注意事项

  1. 类型冲突:合并时类型必须兼容,否则会报错

  2. 模块增强:使用 declare module 语法时需要注意模块路径

  3. 可读性:过度使用声明合并可能会降低代码可读性

http://www.dtcms.com/a/545370.html

相关文章:

  • 做网站组织架构my77728域名查询
  • 深度学习------图像分割项目
  • 【深度学习2】线性回归的从零开始实现
  • LeetCode第2题:两数相加及其变种(某大厂面试原题)
  • Java 字符编码全解析:从乱码根源到 Unicode 实战指南
  • SpringBoot 高效工具类大全
  • 自己做网站用软件wordpress电商优秀
  • 百度网站建设中的自由容器网站用哪个数据库
  • 入侵检测系统——HIDS和NIDS的区别
  • C语言多进程创建和回收
  • 仓颉编程语言:控制流语句详解(if/else)
  • 专利撰写与申请核心要点简报
  • AI搜索引擎num=100参数移除影响深度分析:内容标识与准确性变化
  • NJU-SME 人工智能(三) -- 正则化 + 分类 + SVM
  • 【数据库】表的设计
  • 深圳制作网站建设推广第一网站ppt模板
  • 点网站建设广州专业网站建设哪家公司好
  • 仓颉语言构造函数深度实践指南
  • DTAS 3D-尺寸公差分析定制化服务与解决方案的专家-棣拓科技
  • 永康营销型网站建设wordpress自定义作者连接
  • linux NFS(网络文件系统)挂载完整指南
  • 数字营销软件完整指南|CRM、CDP、自动化平台 2025
  • 企业级建模平台Enterprise Architect如何自动化生成报告
  • Chat2DB 学习笔记
  • 外国做爰网站小程序问答库
  • 关于网站建设方案的案例石家庄建站凡科
  • LeetCode 410 - 分割数组的最大值
  • Kotlin数据结构性能全解析
  • 搜索引擎网站优化和推广方案网站建设招标合同要求
  • coco json 分类标注工具源代码