0

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.

2 Answers 2

1

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)
      }
    }
  }
Sign up to request clarification or add additional context in comments.

Comments

1

The problem here is that localStorage return string | null and isTokenExpired() helper method of jwt takes only string | undefine. value. so you can do something like this. Check if the value is null or not before passing it. Or, if it is null change it’s value to undefined

const lan= localStorage.getItem('language');

if (language)
  this.language = i18n.locale = lang;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.