无法“动态”导入日期-fns/区域设置库- TypeScript给出尝试导入错误

qacovj5a  于 2023-06-30  发布在  TypeScript
关注(0)|答案(1)|浏览(105)

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

{locales: [{code: 'enUS'}, {code: 'deDE'}, {code: 'arAR'}]}

我想使用date-fn库来处理日期格式,但我必须导入整个date-fn/locale,因为我事先不知道需要哪个locale:

import * as dateFnsLocales from 'date-fns/locale';

问题是,一些区域设置采用不同的代码格式(例如,当后端响应包含以下代码时,启用了对多伊奇的支持:'deDE',但对应的date-fns包只是'de'。另一方面,英语的date-fns包是“enUS”,而不仅仅是“en”。
简单的解决方案imho将处理它与一些合并运营商。示例如下:

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']

工作正常。

sirbozc5

sirbozc51#

下面是我使用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);
  });
});

相关问题