我刚接触打字稿并遇到问题:
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;
};
我希望函数的返回类型为'en'或'ar'。我在这里收到错误消息:类型'string'不能分配给类型'“ en” | “ ar””。我该如何解决?
答案 0 :(得分:1)
这是为我解决问题的原因:
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;
};