Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/444.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 分配前使用的Typescript变量_Javascript_Reactjs_Typescript - Fatal编程技术网

Javascript 分配前使用的Typescript变量

Javascript 分配前使用的Typescript变量,javascript,reactjs,typescript,Javascript,Reactjs,Typescript,我在我的Typescript/ReactJS项目中看到一个错误,即在赋值之前使用了变量'myVar'。TS2454 我运行的是TS版本4.2.3,在我的IDE中以及尝试运行代码时都会出现此错误。但是,它在jsFiddle()中运行良好,我不明白为什么会抛出错误,因为变量似乎是声明和检查的: interface testType { id: string, message: string, } let requestType = 'eventCreated'; let testV

我在我的Typescript/ReactJS项目中看到一个错误,即在赋值之前使用了
变量'myVar'。TS2454

我运行的是TS版本4.2.3,在我的IDE中以及尝试运行代码时都会出现此错误。但是,它在jsFiddle()中运行良好,我不明白为什么会抛出错误,因为变量似乎是声明和检查的:

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;
}

是什么导致此失败?

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

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