ts中的函数重载

js 复制代码
message({
  mode: 'mode',
  text: 'text',
  onClose: function () {},
  duration: 3000,
});

message('text');
message('text', function () {});
message('text', 'mode');
message('text', 'mode', 3000);
message('text', 3000);
message('text', 3000, function () {});

export default {};

message 用法有很多。

ts 复制代码
// ts 的用法
function message(
  param1: string | object,
  param2?: number | Function | string 
): void {
  // Function implementation goes here
}

为什么会有ts函数重载?

因为如果没有重载,永远只是很宽泛的类型,any来any去。太多any要ts就没意思了。

js 复制代码
function message(params1: string | object, param2?: any): void

有重载时,编辑器IDE就能提供更精确的提示:

js 复制代码
message('text')
message('text', 'mode')

ts 复制代码
// 没有重载时,这些错误调用不会被检测到
message('text', 'invalid', 'wrong') // 不会报错
message(123, 'mode')                // 不会报错

// 有重载时,TypeScript 会准确报错
message('text', 'invalid', 'wrong') // 错误:第三个参数类型不匹配
message(123, 'mode')                // 错误:第一个参数必须是字符串或对象

完整代码:

ts 复制代码
function message(text: string): void;
function message(text: string, onClose: () => void): void;
function message(text: string, mode: string): void;
function message(text: string, mode: string, duration: number): void;
function message(text: string, duration: number): void;
function message(text: string, duration: number, onClose: () => void): void;
function message(options: { 
  mode: string; 
  text: string; 
  onClose?: () => void; 
  duration?: number 
}): void;

function message(
  param1: string | object,
  param2?: number | Function | string,
  param3?: number | Function
): void {
  // Function implementation goes here
  if (typeof param1 === 'object') {
    // 对象形式调用: message({ mode: 'mode', text: 'text', onClose: function () {}, duration: 3000 })
    const options = param1;
    // 处理选项
  } else {
    const text = param1;
    
    if (typeof param2 === 'function') {
      // message('text', function () {})
      const onClose = param2;
    } else if (typeof param2 === 'string') {
      // message('text', 'mode')
      const mode = param2;
      
      if (typeof param3 === 'number') {
        // message('text', 'mode', 3000)
        const duration = param3;
      }
    } else if (typeof param2 === 'number') {
      // message('text', 3000) 或 message('text', 3000, function () {})
      const duration = param2;
      
      if (typeof param3 === 'function') {
        // message('text', 3000, function () {})
        const onClose = param3;
      }
    }
  }
}

export default {};
相关推荐
源心锁21 小时前
丧心病狂!在浏览器全天候记录用户行为排障
前端·架构
GIS之路21 小时前
GDAL 实现投影转换
前端
烛阴1 天前
从“无”到“有”:手动实现一个 3D 渲染循环全过程
前端·webgl·three.js
BD_Marathon1 天前
SpringBoot——辅助功能之切换web服务器
服务器·前端·spring boot
Kagol1 天前
JavaScript 中的 sort 排序问题
前端·javascript
eason_fan1 天前
Service Worker 缓存请求:前端性能优化的进阶利器
前端·性能优化
光影少年1 天前
rn如何和原生进行通信,是单线程还是多线程,通信方式都有哪些
前端·react native·react.js·taro
好大哥呀1 天前
Java Web的学习路径
java·前端·学习
HashTang1 天前
【AI 编程实战】第 7 篇:登录流程设计 - 多场景、多步骤的优雅实现
前端·uni-app·ai编程
cos1 天前
Fork 主题如何更新?基于 Ink 构建主题更新 CLI 工具
前端·javascript·git