首页 > 解决方案 > 未能“动态”导入 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']

工作得很好。

标签: javascripttypescriptimportlocaledate-fns

解决方案


这是我用于使用 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);
  });
});

推荐阅读