Microsoft/TypeScript

DOM: `Element#matches()` incorrectly narrows types

Open

#63,497 建立於 2026年5月20日

在 GitHub 查看
 (12 留言) (2 反應) (0 負責人)TypeScript (6,726 fork)batch import
Domain: lib.d.tsHelp Wanted

倉庫指標

Star
 (48,455 star)
PR 合併指標
 (平均合併 6天 17小時) (30 天內合併 9 個 PR)

描述

🔎 Search Terms

element matches narrow never

🕗 Version & Regression Information

  • This changed between versions 5.9.3 and 6.0.3

⏯ Playground Link

https://www.typescriptlang.org/play/?ts=6.0.3#code/CYUwxgNghgTiAEEQBd4iQWxAO2QLngAkAVAWQBkBRTHZAbgCgBCdELXAOgymTAAsQAZwAU8AOTBkY+AEp4AMnloanbrwEjxwYNJlA

💻 Code

declare let element: HTMLElement;
!element.matches( 'dt' ) && element.matches( 'dd' )

🙁 Actual behavior

element.matches( 'dd' ) throws a Property 'matches' does not exist on type 'never' compilation error.

🙂 Expected behavior

element.matches( 'dd' ) does not throw any error.

Additional information about the issue

element.matches( 'dt' ) uses the following overload:

matches<K extends keyof HTMLElementTagNameMap>(selectors: K): this is HTMLElementTagNameMap[K];

The return type of element.matches( 'dt' ) is then this is HTMLElementTagNameMap['dt'] that maps to this is HTMLElement.

Since this is HTMLElement:

  • When false, the type of element is HTMLElement (not narrowed further).
  • When false, the type of element is never.

貢獻者指南