facebook / facebook/flow

Generic type capture violates constraints when using union type for possibly null/undefined function parameter

Offen
#4,271 1 Kommentar 0 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen
Vorherrschende Sprache
Rust
Sterne
22.3k
Forks
1.9k
PR-Merge-Kennzahlen
Keine gemergten PRs in 30 T.

Beschreibung

I found a strange behavior with parameter types on generic functions. Flow is not honoring the constraints I put on `` when I use union types to represent a possibly null/undefined value.

```js
function nn(value: T | null | void): T {
if (value === null || value === undefined) {
throw new Error('value cannot be null');
}
return value;
}

function go(maybeNumber?: ?number) {
const definitelyNumber = nn(maybeNumber);
return definitelyNumber > 0; // Flow mistakenly shows an error on this line
}
```

The error is:
```
10: return definitelyNumber > 0; // Flow mistakenly shows an error on this line
^ null. This type cannot be compared to
10: return definitelyNumber > 0; // Flow mistakenly shows an error on this line
^ number
10: return definitelyNumber > 0; // Flow mistakenly shows an error on this line
^ undefined. This type cannot be compared to
10: return definitelyNumber > 0; // Flow mistakenly shows an error on this line
^ number
```

However there shouldn't be any way for `definitelyNumber` to be `null` *or* `undefined` because the function returns `T` which is constrained to be `number`.

That's weird enough, but even weirder is that the following works with *NO ERRORS*!

```js
function nn(value?: ?T): T {
if (value === null || value === undefined) {
throw new Error('value cannot be null');
}
return value;
}

function go(maybeNumber?: ?number) {
const definitelyNumber = nn(maybeNumber);
return definitelyNumber > 0;
}
```

Beitragsleitfaden

Beitragsleitfaden öffnen

Bewertung

Dieses Issue wurde noch nicht bewertet.

Neue Issues direkt in Ihr Postfach

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