简体   繁体   English

TypeScript变量在运行时有效,但在编译过程中会中断-作用域

[英]TypeScript variable works at runtime but breaks during compile - scoping

I'm trying to reference a variable inside a TypeScript function that breaks compile but works fine at run time. 我试图在TypeScript函数中引用一个变量,该变量会中断编译,但在运行时可以正常工作。 This line breaks the compile: 这行中断了编译:

console.log( EXP_SETTINGS.site.userInterface.showPostbackStatusDelay );

在此处输入图片说明

The reason I know it works at runtime is because I did the following: 我知道它在运行时有效的原因是因为我做了以下事情:

  1. Commented out the offending line. 注释掉违规行。
  2. Did a compile in VS2015 Pro - success. 在VS2015 Pro中进行了编译-成功。
  3. Found js file generated by TS compile, which is named JSUI.js. 找到由TS编译生成的js文件,名为JSUI.js。
  4. Inserted the offending line in the precise corresponding place, saved. 将违规行插入精确的对应位置,保存。
  5. Ran my web page in Chrome - no errors - correct value is emitted to console. 在Chrome中运行我的网页-没有错误-向控制台发出了正确的值。

So...clearly the variable I need is available and in global scope, yet TS blows up during compile. 所以...很明显,我需要的变量在全局范围内可用,但TS在编译过程中会崩溃。 How can I solve this? 我该如何解决?

If you're sure that variable is available to you, you can just declare it somewhere (at the base level) in your file: 如果您确定可以使用该变量,则可以在文件中的某个位置(在基本级别)声明它:

declare const EXP_SETTINGS: any; // Replace any with appropriate type

This will allow you to reference it without typescript complaining. 这样您就可以引用它,而不会抱怨打字稿。 If you have a more specific type for it, I would recommend using that instead of any . 如果您有更具体的类型,我建议您使用它而不是any


Or, if you're only using the EXP_SETTINGS variable in one place, or you don't want to include a type for it, you can just manually silence the compiler with a ts-ignore comment: 或者,如果只在一个地方使用EXP_SETTINGS变量,或者不想包含它的类型,则可以使用ts-ignore注释手动将编译器静音:

// @ts-ignore
console.log( EXP_SETTINGS.site... );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM