如何定义一个对象,其项目可以通过 Typescript 中的变量内容访问?

How to define an object whose items can be accessed through a variable content in Typescript?

我是 typescript 的新手,正在尝试根据用户浏览器语言实现内容。许多不同的国家/地区使用相同的语言(具有不同的语言环境键),因此我试图过滤它们以避免从 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];