Home > database >  Variable "theme" is used before being assigned
Variable "theme" is used before being assigned

Time:03-26

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.

CodePudding user response:

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;
  }
}
  • Related