[SOLVED] Variable "theme" is used before being assigned

Issue

enter image description here

I have a variable theme that is bound to get assigned itself a value from the for loop:

let theme: Theme

for (const themeObj of themeList) {
  const [muiThemeName, muiTheme] = Object.entries(themeObj)[0]!;
  if (muiThemeName === themeName) {
    theme = muiTheme;
    break;
  } else theme = defaultTheme;
}

But still the TS Compiler complains that ‘theme’ is unassigned.

I know that I can do theme! to get away with it. But, it doesnt make sense, theme is going to always get assigned with something because if...else is used to assign it.

Thanks.

Solution

Typescript is correct here.

If themeList is an empty array (a perfectly valid value for an array type), then your loop never runs once. In that case no value would ever be assigned.

Instead you should set the default first, then let your loop override it if necessary.

let theme: Theme = defaultTheme;

for (const themeObj of themeList) {
  const [muiThemeName, muiTheme] = Object.entries(themeObj)[0]!;
  if (muiThemeName === themeName) {
    theme = muiTheme;
    break;
  }
}

Answered By – Alex Wayne

Answer Checked By – Pedro (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *