ashfaq.p
ashfaq.p

Reputation: 5487

Handle return type of a function

I'm new to typescript and facing a issue:

type TLang = 'en' | 'ar'

export const getIntlLang = (): 'en' | 'ar' => {
  const validLangs = ['en', 'ar'];
  const urlParams = new URLSearchParams(window.location.search);
  let userLang: TLang = 'ar';
  const customLang = urlParams.get('language') || '';
  if (customLang && validLangs.includes(customLang)) {
    userLang = customLang; // **Type 'string' is not assignable to type** '"en" | "ar"'
  } else {
    const language: TLang =
      window.localStorage && window.localStorage.getItem('language');
    if (language && validLangs.indexOf(language) >= 0) {
      userLang = language;
    }
  }
  updateLang(userLang);
  return userLang;
};

I want the return type of the function to be specifically 'en' or 'ar'. I'm getting the error here that: Type 'string' is not assignable to type '"en" | "ar"'. How should I fix this?

Upvotes: 1

Views: 160

Answers (1)

ashfaq.p
ashfaq.p

Reputation: 5487

Here is what solved the problem for me:

export const getIntlLang = (): TLang => {
  const urlParams = new URLSearchParams(window.location.search);
  let userLang: TLang = 'ar';
  const customLang = urlParams.get(LANGUAGE_KEY);
  if (customLang === 'ar' || customLang === 'en') {
    userLang = customLang;
  } else {
  const language =
    window.localStorage && window.localStorage.getItem(LANGUAGE_KEY);
    if (language === 'en' || language === 'ar') {
      userLang = language;
    }
  }
  updateLang(userLang);
  return userLang;
};

Upvotes: 1

Related Questions