声明合并

声明合并

定义了两个相同名字的函数、接口或类,那么它们会合并成一个类型。

函数的合并

可以使用重载定义多个函数类型:

js 复制代码
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('');
    }
}

接口的合并

接口中的属性在合并时会简单的合并到一个接口中:

js 复制代码
interface Alarm {
    price: number;
}
interface Alarm {
    weight: number;
}
// 等价于
interface Alarm {
    price: number;
    weight: number;
}

ps:合并的属性的类型和属性值必须是唯一的

js 复制代码
interface Alarm {
    price: number;
}
interface Alarm {
    price: number;  // 虽然重复了,但是类型都是 `number`,所以不会报错
    weight: number;
}

interface Alarm {
    price: number;
}
interface Alarm {
    price: string;  // 类型不一致,会报错
    weight: number;
}

interface Cat {
  name:"小橘"
}

interface Cat {
   //编译报错
  name:"小橘1";
  age:3
}

接口中方法的合并,与函数的合并一样:

js 复制代码
interface Alarm {
    price: number;
    alert(s: string): string;
}
interface Alarm {
    weight: number;
    alert(s: string, n: number): string;
}
// 等价于
interface Alarm {
    price: number;
    weight: number;
    alert(s: string): string;
    alert(s: string, n: number): string;
}

类的合并

类的合并与接口的合并规则一致。

相关推荐
朴shu21 小时前
Luckysheet 远程搜索下拉 控件开发 : 揭秘二开全流程
前端
MediaTea1 天前
Python:模块 __dict__ 详解
开发语言·前端·数据库·python
字节跳动开源1 天前
Midscene v1.0 发布 - 视觉驱动,UI 自动化体验跃迁
前端·人工智能·客户端
光影少年1 天前
三维前端需要会哪些东西
前端·webgl
王林不想说话1 天前
React自定义Hooks
前端·react.js·typescript
heyCHEEMS1 天前
Uni-app 性能天坑:为什么 v-if 删不掉 DOM 节点
前端
马致良1 天前
三年前写的一个代码工具,至今已被 AI Coding 完全取代。
前端·ai编程
橙某人1 天前
LogicFlow 交互新体验:让锚点"活"起来,鼠标跟随动效实战!🧲
前端·javascript·vue.js
借个火er1 天前
依赖注入系统
前端
借个火er1 天前
项目介绍与环境搭建
前端