Javascript 分配前使用的Typescript变量
我在我的Typescript/ReactJS项目中看到一个错误,即在赋值之前使用了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
变量'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;
}