【问题标题】:Typescript variable used before being assigned分配之前使用的打字稿变量
【发布时间】:2021-06-22 12:49:30
【问题描述】:

我在我的 Typescript / ReactJS 项目中看到一个错误,提示 Variable 'myVar' is used before being assigned. TS2454

我正在运行 TS 版本 4.2.3,并且当我尝试运行代码时,我的 IDE 中都会出现此错误。但是,它在 jsFiddle (https://jsfiddle.net/d79L4ju8/) 中运行良好,我不明白为什么会抛出错误,因为似乎声明并检查了变量:

interface testType {
    id: string,
    message: string,
}

let requestType = 'eventCreated';
let testVar = true;
let myVar: testType;

if (testVar) {
    myVar = {
        id: 'abc123',
        message: 'message goes here',
    }
}

switch (requestType) {
    case 'eventCreated':
        if (myVar !== undefined) { // error thrown here
            console.log(myVar);
        }
        break;
    case 'eventChanged':
        if (myVar !== undefined) {
            console.log(myVar);
        }
        break;
}

是什么导致这个失败?

【问题讨论】:

标签: javascript reactjs typescript


【解决方案1】:

如果不分配 testVar,则 myVar 将在未初始化的情况下使用。你可以像这样重写代码:

interface testType {
  id: string,
  message: string,
}

let requestType = 'eventCreated';
let testVar = true;
let myVar: testType | undefined = undefined;

if (testVar) {
  myVar = {
      id: 'abc123',
      message: 'message goes here',
  }
}

switch (requestType) {
  case 'eventCreated':
      if (myVar !== undefined) { // error thrown here
          console.log(myVar);
      }
      break;
  case 'eventChanged':
      if (myVar !== undefined) {
          console.log(myVar);
      }
      break;
}

【讨论】:

    【解决方案2】:

    它抛出一个错误,因为变量“myVar”是在一个条件中声明的;可能不会在条件中定义“myVar”,因此 Typescript 会引发错误。

    【讨论】:

      猜你喜欢
      • 2020-05-22
      • 2021-10-09
      • 1970-01-01
      • 2020-07-16
      • 2017-10-13
      • 2017-10-03
      • 1970-01-01
      • 1970-01-01
      • 2019-11-06
      相关资源
      最近更新 更多