Declare a global Typescript variable as type "module"

I have a React type definition file (which is declared using an external module). In my source files, I usually do:

import * as R from "react" 

and then can happily use R.createElement(... etc. in a strongly typed way.

I do not want to import R into each file, but instead use it as a global declaration (yes, I am ready to create a global namespace with a few variables). I tried:

 import * as React from "react"; declare var R : React; 

This does not work, I get "Cannot find name 'React'" . Is there any other way to export the whole module as global?


Edit 1 - I had to clarify: I am wondering how to export the global type definition to a .d.ts file. Therefore, suppose I have already bound R to window . Now I need typescript to know that R is of type React module .

+5
source share
3 answers

use it as global instead

There are two sides: global type declaration for typescript and global variable availability for consuming JavaScript.

Global type declaration

A .d.ts or declaration contributes to the global name declaration space if there is no root level import or export in the file. So, you have a globalreact.d.ts file that will be an edited version of https://github.com/borisyankov/DefinitelyTyped/blob/master/react/react.d.ts of the form declare module R (instead of declare module "react" )

Export global variables

In the case of a browser, you need to put it on the window . So do the following in the makeReactGlobal.ts file:

 var R = require('react'); (<any>window).R = R 

And then in your main application there is this file to make sure that it is executed before any other code.

+4
source

The declare keyword does not declare a variable in the global scope. This keyword is used when there is a variable in the global scope and you want to use it in TypeScript without getting compilation errors.

You can declare a global variable with:

 import * as R from "react"; window.R = R; 
+1
source

As @basarat said, it doesn't seem like that. @ahejlsberg himself weighed the github question: https://github.com/Microsoft/TypeScript/issues/3180#issuecomment-102523512 .

+1
source

All Articles