简体   繁体   English

在分配之前使用变量“值”

[英]Variable 'value' is used before being assigned

My code:我的代码:

function test() {
  let value: number;

  for (let i = 0; i < 10; i++) {
    value = i;
    console.log(value);
  }

  return value;
}

test();

And got this:得到了这个:

Variable 'value' is used before being assigned

I found this very odd, as I had seen other similar problems that either used a callback or a Promise or some other asynchronous method, while I used just a synchronous for loop.我发现这很奇怪,因为我看到了其他类似的问题,这些问题要么使用回调,要么使用 Promise 或其他一些异步方法,而我只使用了同步 for 循环。

Use the non-null assertion operator to ensure that "its operand is non-null and non-undefined in contexts where the type checker is unable to conclude that fact."使用非空断言运算符确保“它的操作数在类型检查器无法得出该事实的上下文中是非空且非未定义的”。

function test() {
  let value!: number;

  for (let i = 0; i < 10; i++) {
    value = i;
    console.log(value);
  }

  return value;
}

test();

Result 结果

TypeScript can't infer that anything in the loop body runs - it doesn't check that i starts at 0, and the condition is i < 10 , and that the body will run at least once as a result. TypeScript 无法推断循环体中的任何内容都在运行 - 它不检查i是否从 0 开始,并且条件是i < 10 ,因此循环体将至少运行一次。 This behavior is very similar to the following:此行为与以下行为非常相似:

function test() {
  let value: number;
  if (Math.random() < 0.5) {
    value = 5;
  }
  return value;
}

which produces the same error.这会产生相同的错误。

For TS to know that the value really definitely is defined at the end, you need to make it completely unambiguous.为了让 TS 知道该值确实在最后定义,您需要使其完全明确。 Usually, the best way this is achieved is by defining and assigning to the variable once , with const , through array methods and helper functions - TS works best when reassignment is minimized.通常,实现这一点的最佳方法是通过数组方法和辅助函数使用const定义和分配一次变量 - TS 在重新分配最小化时效果最佳。

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

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