Typescript Global Variable across Files

2019-06-22 15:00发布

问题:

I created a variable in a .ts file that has no module or class. It mostly looks just like a plain JavaScript file. I want this variable to accessible in another .ts file inside of a class that is inside of a variable.

So for example I have:

foo.ts

var foo = "some stuff";

bar.ts

module Bar {
    export class BarClass {
        function getFoo() {
             return foo;
        }
    }
}

I'm not sure this is the best way to do it. I've tried using the window.bar global but that doesn't seem to work. I'm new to TypeScript jumping into a larger codebase so please let me know if you need any further clarification on anything.

Thanks!

回答1:

TypeScript files don't know about anything you've done in other TypeScript files unless they have a reference to them. So at the top of bar.ts you should have a line

/// <reference path="foo.ts" />


回答2:

From your question, not sure if it was a compilation, IDE or runtime issue that you had. Still, thought I'd share that a good way to avoid some of these issues with globals is to create your own "types" file and list it in your typeRoots property in your tsconfig.json.

For example, something I've done in the past is create a shortcut to console.log that also colours messages with a style I wish. Like so...

const pretty = (style: string, ...anything) => {
  anything.forEach(something => 
    console.log(`%c ${something} `, style));
  return moment().format('[Logged @] HH:MM:SS');
}

So I don't have to declare var pretty in every TS file I use it, I'd create src/myTypes/globals/index.d.ts

...
declare function pretty(style: string, ...anything);
...

And then in my tsconfig.json

{
  "compilerOptions": {
    ...
    "typeRoots": ["src/myTypes"]

So, in your case, if foo was a var that you know would be there in runtime you could simply declare var foo: string; in your types file, list it in your typeRoots and use it happily in all your project files without any further config.