microsoft / microsoft/TypeScript
[TS 4.2] Narrowing a union type is inconsistent using type guards on different member of union
オープン
まだ誰も着手していません。
Bug
Domain: check: Control Flow
- 主要言語
- Go
- スター
- 111k
- フォーク
- 14.4k
- 平均マージ
- 1日 19時間
- マージ済み PR(30日)
- 117
説明
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.
コントリビューションガイド
はじめの一歩
- issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
- 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
- リポジトリをフォークし、ブランチを切って変更します。
- issue 番号を参照したプルリクエストを送ります。
調査の方向性
リンク先の TypeScript Playground の再現例から始め、test() と test2() の相補的な resultIsSuccess ガードと resultIsFailure ガードを比較します。型チェッカーが else ブランチをどのように絞り込むかを追跡します。完了の条件は、報告された TypeScript バージョンで、両方の例が期待どおりに相補的な union member へ一貫して絞り込まれることです。
索引モデルが issue の本文から書いたものです。
評価
- 技術スタック
- typescript
- 領域
- compilers
- issue の種類
- バグ
- 難易度
- 4/5
- 見積もり時間
- 3〜5日
- 活発さ
- 停滞
- 明瞭さ
- おおむね明確
- 初心者へのやさしさ
- 35/100