我是打字新手,尝试实现一个基于用户浏览器语言的内容。许多不同的国家使用相同的语言(具有不同的区域设置键),所以我试图过滤它们以避免从date-fns
(稍后将使用)导入所有区域设置。
const availableLanguages = {
es: 'es',
pt: 'pt-BR',
en: 'en-US'
}
const {i18n} = useTranslation(); // library for getting user locale
const browserLanguage = i18n.language.slice(0,2); // Handles pt-BR x pt-PT
const locale = availableLanguages[browserLanguage] // throws error
最后一行抛出
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ es: string; pt: string; en: string; }'.
No index signature with a parameter of type 'string' was found on type '{ es: string; pt: string; en: string; }'
错误。我该怎么修理它?
首先确保browserLanguage
是对象的键之一:
if (browserLanguage !== 'es' && browserLanguage !== 'pt' && browserLanguage !== 'en') {
// hopefully your app is designed so that this never occurs
// but having this branch will make TS happy
throw new Error('Language is not in availableLanguages');
}
const locale = availableLanguages[browserLanguage]
其他方法需要类型断言,例如:
if (!Object.keys(availableLanguages).includes(browserLanguage)) {
throw new Error('Language is not in availableLanguages');
}
const locale = availableLanguages[browserLanguage as keyof typeof availableLanguages];