Nol*_*ski 6 javascript scope typescript
我在.ts文件中创建了一个没有模块或类的变量.它看起来就像一个普通的JavaScript文件.我希望这个变量可以在变量内部的类中的另一个.ts文件中访问.
所以我举例说:
foo.ts
var foo = "some stuff";
Run Code Online (Sandbox Code Playgroud)
bar.ts
module Bar {
export class BarClass {
function getFoo() {
return foo;
}
}
}
Run Code Online (Sandbox Code Playgroud)
我不确定这是最好的方法.我尝试过使用window.bar全局,但这似乎不起作用.我是TypeScript跳入更大代码库的新手,所以如果您需要进一步澄清任何内容,请告诉我.
谢谢!
TypeScript文件不知道您在其他TypeScript文件中所做的任何事情,除非他们有对它们的引用.所以在bar.ts你的顶部应该有一条线
/// <reference path="foo.ts" />
Run Code Online (Sandbox Code Playgroud)
从您的问题来看,不确定您遇到的是编译、IDE 还是运行时问题。尽管如此,我认为避免全局变量的一些问题的一个好方法是创建您自己的“类型”文件并将其列在您typeRoots的tsconfig.json.
例如,我过去做过的事情是创建一个 console.log 的快捷方式,它也可以用我想要的样式为消息着色。就像这样...
const pretty = (style: string, ...anything) => {
anything.forEach(something =>
console.log(`%c ${something} `, style));
return moment().format('[Logged @] HH:MM:SS');
}
Run Code Online (Sandbox Code Playgroud)
所以我不必declare var pretty在我使用的每个 TS 文件中创建src/myTypes/globals/index.d.ts
...
declare function pretty(style: string, ...anything);
...
Run Code Online (Sandbox Code Playgroud)
然后在我的 tsconfig.json 中
{
"compilerOptions": {
...
"typeRoots": ["src/myTypes"]
Run Code Online (Sandbox Code Playgroud)
因此,在您的情况下,如果foo您知道在运行时会存在一个 var,您可以简单地declare var foo: string;在您的类型文件中,将其列出在您的 typeRoots 中,并在所有项目文件中愉快地使用它,而无需任何进一步的配置。