microsoft / microsoft/TypeScript

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

Đang mở
#63,497 14 bình luận 3 reaction 0 người được giao Xem trên GitHub

Chưa có ai nhận issue này.

Domain: lib.d.ts Help Wanted
Ngôn ngữ chính
Go
Star
111k
Fork
14.3k
Merge trung bình
2 ngày 4 giờ
Pull request đã merge (30 ngày)
132

Mô tả

### 🔎 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

```ts
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:
```ts
matches(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`.

Hướng dẫn đóng góp

Mở hướng dẫn đóng góp

Bắt đầu từ đâu

  1. Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
  2. Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
  3. Fork repository và làm thay đổi trên một nhánh.
  4. Mở pull request có tham chiếu số hiệu của issue.

Hướng nghiên cứu

Bắt đầu với ví dụ TypeScript Playground được liên kết và kiểm tra overload Element#matches được hiển thị trong issue, sau đó theo dõi cách type predicate thu hẹp HTMLElement sau một phép kiểm tra phủ định. Issue hoàn tất khi lần gọi element.matches('dd') thứ hai biên dịch được mà không có lỗi Property 'matches' does not exist on type 'never'.

Do mô hình lập chỉ mục viết ra từ nội dung của issue.

Đánh giá

Công nghệ
typescript
Lĩnh vực
compilers
Loại issue
Lỗi
Độ khó
4/5
Thời gian dự kiến
3-5 ngày
Mức độ hoạt động
Sôi nổi
Độ rõ ràng
Khá rõ ràng
Mức phù hợp với người mới
52/100

Nhận issue mới trong hộp thư của bạn

Bản tóm tắt ngắn những issue GitHub phù hợp với người mới.