首页 > 解决方案 > 分配之前使用的打字稿变量

问题描述

我在我的 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;
}

是什么导致这个失败?

标签: javascriptreactjstypescript

解决方案


如果不分配 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;
}

推荐阅读