Declare Typescript global variable as “module” type

前端 未结 3 1635
情书的邮戳
情书的邮戳 2020-12-18 06:20

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

import * as R from \"react\"

相关标签:
3条回答
  • 2020-12-18 06:47

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

    You can declare a global variable with:

    import * as R from "react";
    window.R = R;
    
    0 讨论(0)
  • 2020-12-18 07:06

    instead have it as a global

    There are two sides to this: global type declaration for typescript and global variable availability for JavaScript consumption.

    Global Type Declaration

    A .d.ts or a declaration only contributes to the global name declaration space if there is no root level import or export in the file. So have a file globalreact.d.ts which 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").

    Global Variable Export

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

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

    And then in your application main have this file a dependency to ensure that it executes before any of your other code.

    0 讨论(0)
  • 2020-12-18 07:12

    Like @basarat said, it doesn't look like it's possible. @ahejlsberg himself weighed in on the issue on github: https://github.com/Microsoft/TypeScript/issues/3180#issuecomment-102523512.

    0 讨论(0)
提交回复
热议问题