I'm seeing an error in my Typescript / ReactJS project saying Variable 'myVar' is used before being assigned. TS2454
I'm running TS version 4.2.3, and this error shows up in my IDE as well as when I try to run the code. However, it works fine in jsFiddle (https://jsfiddle.net/d79L4ju8/) and I don't understand why the error would be thrown, since it seems like the variable is declared and checked:
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;
}
What's causing this to fail?
If testVar would not be assigned, the myVar would be used without being initialized. You could rewrite the code like so:
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With