简体   繁体   English

从外部文件在打字稿中声明var获取ReferenceError:…未定义

[英]Declare var in typescript from external file gets ReferenceError: … is not defined

I have the following typescript file--> 我有以下打字稿文件->

module someModule {
declare var servicePort: string;

export class someClass{
constructor(){
  servicePort = servicePort || ""; //ERROR= 'ReferenceError: servicePort is not defined'
}

also tried this on one of functions inside "someClass" --> 也尝试在“ someClass”内部的功能之一上执行此操作->

someFunction = () => {
    if (servicePort && servicePort != '') { //ERROR - also servicePort is not defined
            //do something with servicePort 
        }
}

If I define var servicePort somewhere on my js /html files it will work, but not all my pages contains the servicePort var, and I want to safe get the value from that varible without exception. 如果我在js / html文件的某处定义var servicePort,它将可以使用,但是并非我的所有页面都包含servicePort var,因此我想毫无例外地从该变量中安全地获取值。 What am I doing wrong? 我究竟做错了什么?

Having a variable sometimes be defined and sometimes not is a pretty big code smell, but if you really want to do this, you need to guard access on that variable with typeof : 有时会定义一个变量,有时不会定义一个变量,这是一个很大的代码味道,但是如果您确实想执行此操作,则需要使用typeof保护对该变量的访问:

if (typeof servicePort !== "undefined") {
   // safe to use servicePort here
}

Note that you won't be able to tell the difference between a missing variable and one with the value undefined , but such is life. 请注意,您将无法分辨缺失变量和值为undefined变量之间的区别,但这就是生命。

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

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