Typescript Global Variable across Files

丶灬走出姿态 提交于 2019-12-19 18:24:44

问题


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.



来源:https://stackoverflow.com/questions/17353192/typescript-global-variable-across-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!