【发布时间】: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