microsoft / microsoft/TypeScript
[TS 4.2] Narrowing a union type is inconsistent using type guards on different member of union
Dieses Issue hat noch niemand übernommen.
- Vorherrschende Sprache
- Go
- Sterne
- 111k
- Forks
- 14.3k
- Ø Merge
- 2 T. 4 Std.
- Gemergte PRs (30 T.)
- 132
Beschreibung
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.
Beitragsleitfaden
Erste Schritte
- Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
- Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
- Forke das Repository und arbeite in einem Branch.
- Öffne einen Pull Request, der die Issue-Nummer nennt.
Rechercherichtung
Beginne mit der verlinkten TypeScript Playground-Reproduktion und vergleiche die komplementären resultIsSuccess- und resultIsFailure-Guards in test() und test2(). Verfolge, wie der Typprüfer die else-Zweige eingrenzt; als abgeschlossen gilt die Aufgabe, wenn beide Beispiele das komplementäre Union-Mitglied in den gemeldeten TypeScript-Versionen konsistent wie erwartet eingrenzen.
Vom Indexierungsmodell aus dem Issue-Text verfasst.
Bewertung
- Tech-Stack
- typescript
- Bereich
- compilers
- Issue-Typ
- Bug
- Schwierigkeit
- 4/5
- Geschätzter Aufwand
- 3-5 Tage
- Aktivitätsstatus
- Veraltet
- Klarheit
- Größtenteils klar
- Anfängerfreundlichkeit
- 35/100