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 {};
相关推荐
西洼工作室43 分钟前
CSS高效开发三大方向
前端·css
昔人'1 小时前
css`font-variant-numeric: tabular-nums` 用来控制数字的样式。
前端·css
铅笔侠_小龙虾1 小时前
动手实现简单Vue.js ,探索Vue原理
前端·javascript·vue.js
哟哟耶耶3 小时前
Starting again-02
开发语言·前端·javascript
Apifox.3 小时前
Apifox 9 月更新| AI 生成接口测试用例、在线文档调试能力全面升级、内置更多 HTTP 状态码、支持将目录转换为模块
前端·人工智能·后端·http·ai·测试用例·postman
Kitasan Burakku3 小时前
Typescript return type
前端·javascript·typescript
叁佰万4 小时前
前端实战开发(一):从参数优化到布局通信的全流程解决方案
前端
笔尖的记忆4 小时前
js异步任务你都知道了吗?
前端·面试
光影少年4 小时前
react生态
前端·react.js·前端框架
golang学习记4 小时前
从0死磕全栈之Next.js 中的错误处理机制详解(App Router)
前端