microsoft / microsoft/TypeScript
This narrowing typeguard effect bleeds into subsequent statments on a type with bivariant type-parameter
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ả
TypeScript Version: 3.4.0-dev.201xxxxx (although 3.3 is also impacted)
Search Terms: this type guards
If we create a type-guard that narrows this on a type that has a type-parameter that is present only in a bivariant position, the effect of the type guard persists outside of the guarded block.
Code
type GetKnownKeys<G> = G extends GuardedMap<infer KnownKeys> ? KnownKeys: never;
interface GuardedMap<KnownKeys extends string> {
get(k: KnownKeys): number;
has<S extends string>(k: S): this is GuardedMap<S | GetKnownKeys<this>>;
}
declare let map: GuardedMap<never>;
map.get('bar') // err, as expected
if (map.has('foo')) {
map.get('foo').toExponential(); // ok as expected
if(map.has('bar'))
{
map.get('foo').toExponential(); // ok as expected
map.get('bar').toExponential(); // ok as expected
}
map.get('bar').toExponential(); /// OK!?!?! WHY ?!
}
map.get('bar') // OK ?!
Expected behavior:
Type guard only impacts the guarded block.
Actual behavior:
The effect of the type guard bleads into all subsequent statements. (marked with OK!?!?! and OK?!)
Note: With strictFunctionTypes on, declaring get as get: (k: KnownKeys) => number; makes the code work as expected.
Playground Link: link
Related Issues: Similar to #14817
Found this while playing with a solution for #9619
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
Tái hiện lỗi rò rỉ narrowing trong TypeScript Playground được liên kết bằng ví dụ GuardedMap được cung cấp. Theo dõi cách trình biên dịch xử lý control flow cho các type guard của this và các tham số kiểu bivariant; hoàn thành khi narrowing vẫn bị giới hạn trong block được bảo vệ và map.get('bar') sau block bị từ chối, kèm theo coverage hồi quy.
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
- 38/100