microsoft / microsoft/TypeScript

Typescript 4.2.x - incorrectly infered generic return type of a record union (extra undefined)

Offen
#43,943 2 Kommentare 1 Reaktion 1 zugewiesene Person Auf GitHub ansehen

@andrewbranch arbeitet bereits daran.

Seit 04.5.2021.

Bug Domain: check: Type Inference Has Repro
Vorherrschende Sprache
Go
Sterne
111k
Forks
14.3k
Ø Merge
2 T. 4 Std.
Gemergte PRs (30 T.)
132

Beschreibung

Bug Report

🔎 Search Terms

undefined, generic inference, typescript 4.2

🕗 Version & Regression Information

4.2.0-beta - 4.3.0-dev.20210504 (everything since 4.2 beta, including all stable releases)
NOT in 4.1.x or before

  • This changed between versions 4.1.x and 4.2.x+

The return type inference of the the arrow function hasn't changed, according to the playground it was always infered as { kind: "failure"; value?: undefined; } | { kind: "success"; value: number; }. However, before 4.2. the type of the generic function above it (the andThen) was correctly narrowed down to AndThenResult<number>. This happened even without explicit type annotations, as one would expect.

In 4.2+ the undefined gets propagated into andThen<number | undefined> and this breaks the assignment (and my expectations).

⏯ Playground Link

Playground link with relevant code

💻 Code
// @strict: true
type AndThenResult<T> = { kind: 'success', value: T } | { kind: 'failure' };

function andThen<U>(
    fun: (_: number) => AndThenResult<U>
) {
    return fun(1)
}
//    V error here, type inference gets `AndThenResult<number | undefined>` from `andThen` in TS 4.2+
const a: AndThenResult<number> = andThen(
    // looks like this function infers { kind: "failure"; value?: undefined; } | { kind: "success"; value: number; } on any TS version in the playground
    // however the undefined only gets propagated up in 4.2+
    x => {
        if (x === 1) {
            return { kind: 'failure' }
        }
        return {
            kind: 'success',
            value: x
        }
    }
)
🙁 Actual behavior

The types don't match and the code doesn't compile. The return type of andThen(fn) is different than that expected on a.

🙂 Expected behavior

The types do match, the function return type is narrowed to AndThenResult<number> and nothing breaks.

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.