Skip to content

fix: Fixes an issue where the target does not accept the ref type when using explicit generics with useEventListener. - #2903

Merged
crazylxr merged 1 commit into
alibaba:masterfrom
Arktomson:fix/issue-2902_useEventListener-types
Mar 28, 2026
Merged

fix: Fixes an issue where the target does not accept the ref type when using explicit generics with useEventListener.#2903
crazylxr merged 1 commit into
alibaba:masterfrom
Arktomson:fix/issue-2902_useEventListener-types

Conversation

@Arktomson

Copy link
Copy Markdown
Contributor

🤔 这个变动的性质是?

  • 新特性提交
  • 日常 bug 修复
  • 站点、文档改进
  • 演示代码改进
  • TypeScript 定义更新
  • 包体积优化
  • 性能优化
  • 功能增强
  • 国际化改进
  • 重构
  • 代码风格优化
  • 测试用例
  • 分支合并
  • 其他改动(是关于什么的改动?)

🔗 相关 Issue

💡 需求背景和解决方案

Issue #2902 中,useEventListener 在显式指定事件泛型参数时(例如 useEventListener<'scroll'>),options.target 的类型推导会退化为 HTMLElement 本体,导致 ref(如 RefObject<HTMLDivElement | null>)无法通过类型检查。

具体修复:

  1. 调整 useEventListener 内部 Options<T> 类型定义:
    • target?: T
    • 改为 target?: BasicTarget<T>
  2. 保持现有运行时逻辑不变,仅修复类型约束语义。
  3. 新增回归测试,覆盖“显式泛型 + ref target”场景,防止后续回归。

涉及文件:

  • packages/hooks/src/useEventListener/index.ts
  • packages/hooks/src/useEventListener/__tests__/index.spec.ts

📝 更新日志

语言 更新描述
🇺🇸 英文 Fixed useEventListener typing to accept ref targets when event generic is explicitly specified (e.g. useEventListener<'scroll'>). Added a regression test for this scenario.
🇨🇳 中文 修复 useEventListener 在显式指定事件泛型(如 useEventListener<'scroll'>)时 target 不能接收 ref 的类型问题,并补充对应回归测试。

☑️ 请求合并前的自查清单

  • 文档已补充或无须补充
  • 代码演示已提供或无须提供
  • TypeScript 定义已补充或无须补充
  • Changelog 已提供或无须提供

@pkg-pr-new

pkg-pr-new Bot commented Feb 12, 2026

Copy link
Copy Markdown
npm i https://pkg.pr.new/ahooks@2903
npm i https://pkg.pr.new/@ahooksjs/use-url-state@2903

commit: eb7c605

@meet-student

Copy link
Copy Markdown
Collaborator

你这个所有的 title 都改成 英文吧, 等下我找 萧看下

@Arktomson

Arktomson commented Feb 24, 2026 via email

Copy link
Copy Markdown
Contributor Author

@Arktomson Arktomson changed the title fix: 修复 useEventListener 显式泛型时 target 不接受 ref 的类型问题 fix: Fixes an issue where the target does not accept the ref type when using explicit generics with useEventListener. Feb 24, 2026
@crazylxr

Copy link
Copy Markdown
Collaborator

LGTM,这个修复方向没问题,直接命中了显式泛型场景下 target 不能接收 ref 的根因。补的回归用例也比较到位,而且这条用例会参与 TypeScript 检查,能防住后续类似回归。

@crazylxr
crazylxr merged commit 454b65b into alibaba:master Mar 28, 2026
9 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

useEventListener 指定泛型的第一个参数后 options参数ts类型声明无法接收ref作为target

3 participants