microsoft / microsoft/TypeScript

Incorrect generic inference inside a discriminated union

Offen
#45,809 3 Kommentare 3 Reaktionen 1 zugewiesene Person Auf GitHub ansehen

@weswigham arbeitet bereits daran.

Seit 10.9.2021.

Bug Domain: check: Type Inference Rescheduled
Vorherrschende Sprache
Go
Sterne
111k
Forks
14.4k
Ø Merge
1 T. 19 Std.
Gemergte PRs (30 T.)
117

Beschreibung

Bug Report

🔎 Search Terms

discrimated union generic extra property

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

Playground link with relevant code

💻 Code
type Loadable<TValue> =
    | {
          state: "loading"
      }
    | {
          state: "complete"
          value: TValue
      }


function mapLoadable<TValue>(loadable: Loadable<TValue>, map: (value: TValue) => void): void {
}

type AugmentedLoadable =
    | {
          state: "loading"
          value: number
      }
    | {
          state: "complete"
          value: string
      }

function mapAugmented(augmented: AugmentedLoadable) {
    mapLoadable(augmented, () => {}) // ❌ Errors with "Argument of type 'AugmentedLoadable' is not assignable to parameter of type 'Loadable<number>'"
    mapLoadable<string>(augmented, () => {}) // ✅ Works now that type is generic is specified
}
🙁 Actual behavior

TypeScript incorrectly infers that augmented should be assignable to Loadable<number> rather than a Loadable<string>, because we've added an unrelated value: number property to it. It can be nudged into working by writing out the generic type.

🙂 Expected behavior

TypeScript to infer the correct generic of string.

Beitragsleitfaden

Beitragsleitfaden öffnen

Erste Schritte

  1. Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
  2. Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
  3. Forke das Repository und arbeite in einem Branch.
  4. Öffne einen Pull Request, der die Issue-Nummer nennt.

Bewertung

Dieses Issue wurde noch nicht bewertet.

Neue Issues direkt in Ihr Postfach

Eine kurze Übersicht über anfängerfreundliche GitHub-Issues.