Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript variable used before being assigned

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?

like image 300
user101289 Avatar asked Jun 22 '26 11:06

user101289


1 Answers

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;
}
like image 107
Belvain Avatar answered Jun 24 '26 23:06

Belvain



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!