You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript工具函数传参报错:期望1个参数却传入0个求助

问题原因

你遇到的报错是因为TypeScript判定DetectMobile函数必须接收一个参数——虽然你给解构的breakpoint属性加了默认值,但整个函数参数(那个对象)并没有设置默认值。TS的类型定义DetectMobileProps里的属性是可选的,但函数本身要求传入一个该类型的参数,不传就不符合类型约束。

解决方案

给函数的参数设置默认空对象,这样不传参数时会自动使用这个默认值,解构时breakpoint会 fallback 到你设置的"768px"。修改函数定义如下:

export function DetectMobile({ breakpoint = "768px" }: DetectMobileProps = {}) {
  // 原有逻辑...
}

现在你可以直接调用const { isMobile } = DetectMobile();,无需传空对象。

额外优化建议

你的代码还有两个潜在问题,建议一起修复:

  1. useEffect依赖缺失:当前useEffect的依赖数组是空的,但里面用到了breakpoint。如果后续传入自定义断点,useEffect不会重新执行监听,导致逻辑错误。需要把breakpoint加入依赖:
useEffect(() => {
  const mediaWatcher = window.matchMedia(`(max-width: ${breakpoint})`);
  setIsMobile(mediaWatcher.matches);

  function updateIsMobile(event) {
    setIsMobile(event.matches);
  }

  mediaWatcher.addEventListener("change", updateIsMobile);
  
  // 组件卸载时移除监听,避免内存泄漏
  return () => {
    mediaWatcher.removeEventListener("change", updateIsMobile);
  };
}, [breakpoint]); // 加入breakpoint依赖
  1. 冗余的useMemo:isMobile只是直接返回isMobileDevice,这种情况下useMemo完全没必要,直接用isMobileDevice或者返回时写return { isMobile: isMobileDevice };即可,能简化代码。

修改后的完整代码示例:

import { useEffect, useState } from "react";

type DetectMobileProps = {
  breakpoint?: string;
};

export function DetectMobile({ breakpoint = "768px" }: DetectMobileProps = {}) {
  const [isMobile, setIsMobile] = useState(false);

  useEffect(() => {
    const mediaWatcher = window.matchMedia(`(max-width: ${breakpoint})`);
    setIsMobile(mediaWatcher.matches);

    const updateIsMobile = (event: MediaQueryListEvent) => {
      setIsMobile(event.matches);
    };

    mediaWatcher.addEventListener("change", updateIsMobile);
    
    return () => {
      mediaWatcher.removeEventListener("change", updateIsMobile);
    };
  }, [breakpoint]);

  return { isMobile };
}

内容的提问来源于stack exchange,提问作者user3330820

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 05:35:05