microsoft / microsoft/TypeScript
Narrowing from `typeof x !== 'object'` incorrectly excludes functions.
Chưa có ai nhận issue này.
- Ngôn ngữ chính
- Go
- Star
- 111k
- Fork
- 14.4k
- Merge trung bình
- 1 ngày 19 giờ
- Pull request đã merge (30 ngày)
- 117
Mô tả
Bug Report
🔎 Search Terms
typeof object function narrow, type narrowing
🕗 Version & Regression Information
Present in all recent versions from at least 3.3.3333 through the current nightly 4.4.0-dev.20210701
- This is the behavior in every version I tried, and I reviewed the FAQ for entries about "typeof" and "narrow"
⏯ Playground Link
💻 Code
let x!: string|object; // |Function;
if (1 < 2) x = () => 1;
if (typeof x !== 'object') {
useString(x); // should fail, but doesn't
}
declare function useString(s: string): void;
🙁 Actual behavior
The type narrowing for typeof x !== 'object' pruned the entire |object branch from x's type union, but typeof can return either "object" or "function" for values of type object, so this is overzealous. This causes x inside the conditional to be incorrectly narrowed to just string when we can clearly see from the earlier line that it's been assigned a function, which is incorrectly passed to useString with no complaint.
🙂 Expected behavior
Excluding "object" from typeof x should not remove |object from its type, in the same way that it doesn't narrow unknown any further. This would cause the appropriate type error from passing a function to useString.
Note that if an explicit |Function branch is added to to x's type union then the narrowing proceeds as expected.
Hướng dẫn đóng góp
Bắt đầu từ đâu
- Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
- 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.
- Fork repository và làm thay đổi trên một nhánh.
- Mở pull request có tham chiếu số hiệu của issue.
Hướng nghiên cứu
Bắt đầu với TypeScript Playground được liên kết và ví dụ narrowing được cung cấp, sau đó lần theo logic narrowing kiểu cho typeof x !== "object". Bản sửa hoàn tất khi một hàm được gán cho x không bị loại bỏ bởi narrowing và việc truyền x vào useString tạo ra lỗi kiểu như mong đợi; hãy kiểm tra hành vi dựa trên các phiên bản đã nêu.
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
- Đình trệ
- Độ rõ ràng
- Đặc tả rõ ràng
- Mức phù hợp với người mới
- 45/100