microsoft / microsoft/TypeScript

[TS 4.2] Narrowing a union type is inconsistent using type guards on different member of union

Đang mở
#43,904 1 bình luận 0 reaction 0 người được giao Xem trên GitHub

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

Bug Domain: check: Control Flow
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ả

Bug Report

🔎 Search Terms

narrowing union type

🕗 Version & Regression Information
  • This changed between versions 4.1.5 and 4.2.3
⏯ Playground Link

Playground link with relevant code

💻 Code
export type SuccessStatusCode = 200 | 201
export type FailureStatusCode = 400 | 401 | 402 | 403 | 500 | 502

interface HttpResponse<StatusCode extends SuccessStatusCode | FailureStatusCode> {
  statusCode: StatusCode
}

interface LegacyApiResponse extends Partial<{ [key: string]: unknown }> {
	statusCode?: never
}

type Success = HttpResponse<SuccessStatusCode> | LegacyApiResponse
type Failure = HttpResponse<FailureStatusCode>

type Result<S extends Success, F extends Failure = never> = S | F

declare function resultIsSuccess<S extends Success, F extends Failure>(r: Result<S, F>): r is S
declare function resultIsFailure<S extends Success, F extends Failure>(r: Result<S, F>): r is F

type TestResult = Result<{ success: true }, HttpResponse<403>>

declare const result: TestResult

export function test() {
  if (resultIsFailure(result)) {
    result // Inferred as HttpResponse<403>.
  } else {
    result // Inferred as { success: true }.
  }
}

export function test2() {
  if (resultIsSuccess(result)) {
    result // Inferred as { success: true }.
  } else {
    result // Cannot infer, stay as TestResult.
  }
}
🙁 Actual behavior

While test1 works fine, in test2, the else branch cannot narrow the type to HttpResponse<403>.

🙂 Expected behavior

test1 and test2 are just narrowing down result using complementary type guards, their behavior should be consistent.
And they are consistent in 4.1.

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 reproduction TypeScript Playground được liên kết và so sánh các guard bổ sung resultIsSuccess và resultIsFailure trong test() và test2(). Theo dõi cách trình kiểm tra kiểu thu hẹp các nhánh else; hoàn tất có nghĩa là cả hai ví dụ đều nhất quán thu hẹp thành union member bổ sung như mong đợi trong các phiên bản TypeScript được báo cáo.

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
Khá rõ ràng
Mức phù hợp với người mới
35/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.