javascript - 未能“动态”导入 date-fns/locale 库 - TypeScript 给出尝试导入错误
问题描述
我有一个应用程序从后端接收支持的语言环境列表作为以下响应:
{locales: [{code: 'enUS'}, {code: 'deDE'}, {code: 'arAR'}]}
我想使用 date-fn 库来处理日期格式,但我必须导入整个 date-fn/locale,因为我事先不知道需要哪个语言环境:
import * as dateFnsLocales from 'date-fns/locale';
问题是,某些语言环境的代码格式不同(例如,当后端响应包含代码:'deDE' 时,启用对德语的支持,但对应的 date-fns 包只是'de'。另一方面英文的 hand date-fns 包是“enUS”,而不仅仅是“en”。
恕我直言,简单的解决方案是使用一些合并运算符来处理它。示例如下:
import * as dateFnsLocales from 'date-fns/locale';
const supportedLocales = {locales: [{code: 'enUS'}, {code: 'deDE'}, {code: 'plPL'}]}
const newArrayWithSupportedLocales = supportedLocales.locales.map((locale) => ({
...locale,
dateFnsLocale: (dateFnsLocales[locale.code] || dateFnsLocales[locale.code.substring(0,2)]),
}));
不幸的是,我收到了打字稿错误:
No index signature with a parameter of type 'string' was found on type 'typeof import("date-fns/locale")'. TS7053
即使我像这样对尝试进行硬编码:
dateFnsLocale: dateFnsLocales['plPL'.substring(0,2)]
它失败并出现相同的错误,即使这样:
dateFnsLocale: dateFnsLocales['pl']
工作得很好。
解决方案
这是我用于使用 ExpoLocalization
对象进行动态查找的代码。
import * as Localization from 'expo-localization';
import * as Locales from 'date-fns/locale';
import { Locale } from 'date-fns';
/**
* Looks up a date-fns locale from the Expo localization object. This falls back to `en-US`
* @param localization Expo Localization object containing the locale and region.
* @returns date-fns locale.
*/
export function getDateFnsLocale({ locale, region }: Pick<typeof Localization, 'locale'|'region'>) : Locale {
return (
Locales[locale.substring(0, 2) + region] ?? Locales[locale.substring(0, 2)] ?? Locales.enUS
);
}
这是测试
import { enUS, fr, frCA } from 'date-fns/locale';
describe('date-fns locale lookup', () => {
it('shound find fr', () => {
expect(getDateFnsLocale({ locale: 'fr', region: null })).toBe(fr);
});
it('shound find fr-CA', () => {
expect(getDateFnsLocale({ locale: 'fr-CA', region: 'CA' })).toBe(frCA);
});
it('shound not find zz-ZZ', () => {
expect(getDateFnsLocale({ locale: 'zz-ZZ', region: 'ZZ' })).toBe(enUS);
});
});
推荐阅读
- angular - NGRX 链式选择器返回嵌套的 momoized 选择器问题
- python - 在 NaN 上连接线而不从数据框中删除整行
- python - 如何删除 Python 字符串中以大写字母开头的子字符串?
- elasticsearch - 用于多选的 Elasticsearch 聚合查询
- python - 无需外部库即可替代 pandas 合并
- flutter - 有没有办法在 Flutter 中捕获全景图像?
- python-3.x - eland是否支持嵌套结构
- api - 不记名令牌超出 OAUTH 设置 - 关于正确使用标准的问题
- mysql - 在mysql中选择基于条件的记录
- audio - 我如何获得