Skip to content

Instantly share code, notes, and snippets.

@pbjorklund
Last active March 28, 2016 17:46
Show Gist options
  • Select an option

  • Save pbjorklund/248dfbd72fb93d2723b1 to your computer and use it in GitHub Desktop.

Select an option

Save pbjorklund/248dfbd72fb93d2723b1 to your computer and use it in GitHub Desktop.
The node ambient module defines a require with type NodeRequire which means that var require : any will claim that it needs type NodeRequire.
Doesn't seem like requirejs typings define RequireConfig anymore either?
var require = {
paths: {
"jquery": "../bower_components/jquery/dist/jquery"
}
};
will yield
src\require-config.ts(1,5): error TS2403: Subsequent variable declarations must have the same type. Variable 'require' must be of type 'NodeRequire', but here has type 'any'.
@nycdotnet

Copy link
Copy Markdown

I can see how that would be a problem. RequireJS functionality beyond the generic AMD functionality will require a typings file, but if you're not using much of it beyond the initial setup, it's not absolutely needed. It depends on how strict you want to be with your types - sometimes it's useful and sometimes it's just a sacrifice to the gods of type safety. This is the problem with global variables - require means different things in different parts of your program.

Put this and let me know if it works:

declare var require: NodeRequire;  // this line may or may not be needed
(() => {
   // you will have strong typing here for the Require.js config setup
  // and with the IIFE your variable will only live here so you're not doing extra
  // global scope pollution
  var myUniqueRequireVariableToNotStepOnNode: RequireConfig = { 
     paths: { 
         "jquery": "../bower_components/jquery/dist/jquery" 
     } 
  };
  // this will allow you to assign that variable to require without TS being mad.
  require = <any>myUniqueRequireVariableToNotStepOnNode;
});

@nycdotnet

Copy link
Copy Markdown

Actually I think it may be necessary to get rid of the declare statement - but otherwise I think this should work OK. The thing with declare is that it removes the emit of the var keyword entirely and then you'll be creating an accidental global which is an error in strict mode. Otherwise this should hopefully cover you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment