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 {};
相关推荐
卓伊凡2 小时前
非常经典的Android开发问题-mipmap图标目录和drawable图标目录的区别和适用场景实战举例-优雅草卓伊凡
前端
前端Hardy2 小时前
HTML&CSS: 谁懂啊!用代码 “擦去”图片雾气
前端·javascript·css
前端Hardy2 小时前
HTML&CSS:好精致的导航栏
前端·javascript·css
天下无贼2 小时前
【手写组件】 Vue3 + Uniapp 手写一个高颜值日历组件(含跨月补全+今日高亮+选中状态)
前端·vue.js
我是天龙_绍2 小时前
🔹🔹🔹 vue 通信方式 eventBus
前端
一个不爱写代码的瘦子3 小时前
迭代器和生成器
前端·javascript
拳打南山敬老院3 小时前
漫谈 MCP 构建之概念篇
前端·后端·aigc
前端老鹰3 小时前
HTML <output> 标签:原生表单结果展示容器,自动关联输入值
前端·html
OpenTiny社区3 小时前
OpenTiny NEXT 内核新生:生成式UI × MCP,重塑前端交互新范式!
前端·开源·agent