Search code examples
typescripteslinttslint

Error: "Type 'string | null' is not assignable ..." when getting Item from LocalStorage


As I understand that I cannot assign null to a string variable. I do not understand why the if clause to check that localStorage.getItem('language') is set isnt resolving this issue.

Error: Type 'string | null' is not assignable to type 'string'. Type 'null' is not assignable to type 'string'.

  setLanguage(lang: string) {
    if (lang) {
      this.language = i18n.locale = lang
      localStorage.setItem('language', lang)
    } else {
      if (localStorage.getItem('language')) {
        this.language = i18n.locale = localStorage.getItem('language')
      } else {
        let browserLang = navigator.language.split('-')[0]
        this.language = i18n.locale = browserLang
        localStorage.setItem('language', browserLang)
      }
    }
  }

thanks.


Solution

  • I think it stems from the fact that you are not assigning it to a variable. The first time and second time you call localStorage.getItem('language') might return different result (as far as the typescript compiler is concerned).
    You might want to try something like:

      setLanguage(lang: string) {
        if (lang) {
          this.language = i18n.locale = lang
          localStorage.setItem('language', lang)
        } else {
          const lang: string | null = localStorage.getItem('language'); // Notice how I'm setting a new variable here
          if (lang) {
            this.language = i18n.locale = lang;
          } else {
            let browserLang = navigator.language.split('-')[0]
            this.language = i18n.locale = browserLang
            localStorage.setItem('language', browserLang)
          }
        }
      }