typescript 变量 'xxx' 在被赋值之前被使用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/59325106/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 05:52:02  来源:igfitidea点击:

Variable 'xxx' is used before being assigned

javascriptnode.jstypescript

提问by Sandro Rey

I have this piece of code

我有这段代码

  let hostel : HostelType;

              hostels.forEach( (r) => {
                  const i =  r.identifier.findIndex((_identifier: any) => _identifier.id === '433456');
                  hostel = hostels[i];
              });

              hostel.serviceLevel.value = 'P';

but I have a compilation error:

但我有一个编译错误:

 Variable 'hostel' is used before being assigned.

采纳答案by Maxim Palenov

You should be sure that there is an instance assigned:

您应该确保分配了一个实例:

let hostel : HostelType;

hostels.forEach( (r) => {
  const i =  r.identifier.findIndex((_identifier: any) => _identifier.id === '433456');

  if (i === -1 || !hostels[i]) {
    throw new Exception('There is no hostel');
  }

  hostel = hostels[i];
});

hostel.serviceLevel.value = 'P';

Ideally the code should be something like that:

理想情况下,代码应该是这样的:

const hostel = hostels.find(x => x.identifier === '433456');

It's not clear why identifieris an array and how it's related to the index in the hostelsarray.

目前尚不清楚为什么identifier是数组以及它与hostels数组中的索引有何关系。

回答by Royce

You are using it before being initialized.

您在初始化之前正在使用它。

You need to initialize it before the loop with something like hostel = new HostelType();

你需要在循环之前用类似的东西初始化它 hostel = new HostelType();

回答by LeGEC

You either need to initialize hostelbefore using it in your hostel.serviceLevel.value = 'P';statement,
or check if it is indeed defined :

您要么需要hostelhostel.serviceLevel.value = 'P';语句中使用它之前进行初始化,
要么检查它是否确实已定义:

if (typeof hostel !== 'undefined') {
    hostel.serviceLevel.value = 'P';
}


The hostelvariable may be undefined :

hostel变量可以是不确定的:

  • if hostelsis empty (the code inside the callback will never be called),
  • if the last element in hostelscontains an identifier whose idfield matches 433456(iwill be -1on the last iteration)
  • 如果hostels为空(回调中的代码永远不会被调用),
  • 如果中的最后一个元素hostels包含一个标识符,其id字段匹配433456i-1在最后一次迭代中)