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 {};
相关推荐
Cache技术分享4 分钟前
435. Java 日期时间 API - Clock 灵活获取当前时间
前端·后端
独泪了无痕1 小时前
Vue3中防御XSS攻击的“特效药”-DOMPurify
前端·vue.js·安全
小小19922 小时前
idea 配置less转化为css
前端·css·less
hhb_6182 小时前
Less嵌套避坑:优先级冲突实战解析
前端·css·less
云水一下2 小时前
Vue.js从零到精通系列(五):全局状态管理——Pinia 核心与实践
前端·javascript·vue.js
我不是外星人2 小时前
浅谈我对 AI 发展的看法
前端·ai编程·claude
甲维斯3 小时前
测一波Kimi K2.7,消耗一周配额!
前端·人工智能·游戏开发
Dick5073 小时前
ROS2 多机器人通用 Driver 层复盘:BaseRobotDriver 到多平台 Mock 切换实现
前端·javascript·机器人
xiaofeichaichai3 小时前
前端安全 XSS 与 CSRF
前端·安全·xss