Typescript Global Variable across Files

2019-06-22 14:30发布

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!

2条回答
神经病院院长
2楼-- · 2019-06-22 14:49

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.

查看更多
再贱就再见
3楼-- · 2019-06-22 14:59

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" />
查看更多
登录 后发表回答