Skip to content

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

@dxu

Description

@dxu

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions