microsoft / microsoft/TypeScript
[TS 4.2] Narrowing a union type is inconsistent using type guards on different member of union
Nessuno ha ancora preso questa issue.
- Lingua principale
- Go
- Stelle
- 111k
- Fork
- 14.3k
- Merge medio
- 2g 4h
- PR unite (30g)
- 132
Descrizione
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.
Guida per i contributori
Apri la guida per i contributori
Come iniziare
- Leggi tutta la issue e poi la guida ai contributi del progetto.
- Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
- Fai un fork del repository e lavora su un branch.
- Apri una pull request che faccia riferimento al numero della issue.
Direzione di ricerca
Inizia con la riproduzione collegata in TypeScript Playground e confronta i guard complementari resultIsSuccess e resultIsFailure in test() e test2(). Traccia il modo in cui il type checker restringe i rami else; il lavoro è completato quando entrambi gli esempi restringono coerentemente il membro complementare dell’unione come previsto nelle versioni di TypeScript riportate.
Scritto dal modello di indicizzazione a partire dal testo della issue.
Valutazione
- Stack tecnologico
- typescript
- Ambito
- compilers
- Tipo di issue
- Bug
- Difficoltà
- 4/5
- Tempo stimato
- 3-5 giorni
- Stato di attività
- Ferma
- Chiarezza
- Abbastanza chiara
- Idoneità per principianti
- 35/100