facebook / facebook/flow

Dynamic `typeof` test with union types outside do not carry into closure scope

Open
#3,369 2 comments 0 reactions 0 assignees View on GitHub
Dominant language
Rust
Stars
22.3k
Forks
1.9k
PR merge metrics
No merged PRs in 30d

Description

Hi, I'm running into an issue that I think may be a bug. It seems like dynamic `typeof` tests on union types aren't respected within closures.

For example:

```
function b(url: string | Object) {
if (typeof url === 'string') {
return new Promise(function(resolve, reject) {
var request = new XMLHttpRequest();
request.open('GET', url)
});
}
}

// For some reason it works when request is shadowed
function b(url: string | Object) {
if (typeof url === 'string') {
// request is shadowed
return new Promise(function(resolve, request) {
var request = new XMLHttpRequest();
request.open('GET', url);
});
}
}

// Another closure via function declaration
function b(url: string | Object) {
if (typeof url === 'string') {
const a = function(resolve, reject) {
const request = new XMLHttpRequest();
request.open('GET', url)
};
}
}
```

gives the errors

```
5: request.open('GET', url)
^ object type. This type is incompatible with the expected param type of
[LIB] static/v0.39.0/flowlib/bom.js:488: open(method: string, url: string, async?: boolean, user?: string, password?: string): void;
^ string
26: request.open('GET', url)
^ object type. This type is incompatible with the expected param type of
[LIB] static/v0.39.0/flowlib/bom.js:488: open(method: string, url: string, async?: boolean, user?: string, password?: string): void;

```

I would expect that due to the `typeof` test on `url` outside the scope, and because i'm not reassigning `url`, this would return no errors.

Thanks for all of your continued great work! Please let me know if I'm making a mistake here.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.