我在我的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;
}是什么原因导致此操作失败?
发布于 2021-03-26 01:07:42
如果不分配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;
}https://stackoverflow.com/questions/66804267
复制相似问题