javascript - 未能 "dynamically"导入 date-fns/locale 库 - TypeScript 给出尝试导入错误

标签 javascript typescript import locale date-fns

我有一个应用程序从后端接收支持的语言环境列表作为以下响应:

{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)]),
      }));
不幸的是,我收到了 typescript 错误: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']
工作得很好。

最佳答案

这是我使用 Expo 的 Localization 进行动态查找的代码目的。

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);
  });
});

关于javascript - 未能 "dynamically"导入 date-fns/locale 库 - TypeScript 给出尝试导入错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66657997/

相关文章:

java - 在 Java 中重构 Import 语句

javascript - require() 相当于 if import { Something } from 'somewhere'

javascript - 如何使用 VSCode 调试 CLI?

javascript - 使 html 类的所有元素对单击使用react,这将修改元素本身

javascript - 在 IONIC2 中获取动态创建的 ionic 输入值

angular - 在 TypeScript.2.7 中找不到名称 'TextDecoder'

python - pylint 无法识别某些标准库

javascript - 在使用 async 和声明性方法使用 observable 测试 Angular 组件时,获取 TypeError 管道不是函数

javascript - 删除表行不应允许删除最后一行

typescript - 如果我的用户群使用 Chrome,那么以 ES6 为目标安全吗?