我有一个应用程序从后端接收支持的区域设置列表作为以下响应:
{locales: [{code: 'enUS'}, {code: 'deDE'}, {code: 'arAR'}]}
Run Code Online (Sandbox Code Playgroud)
我想使用 date-fn 库来处理日期格式,但我必须导入整个 date-fn/区域设置,因为我无法事先知道需要哪个区域设置:
import * as dateFnsLocales from 'date-fns/locale';
Run Code Online (Sandbox Code Playgroud)
问题是,某些语言环境的代码格式不同(例如,当后端响应包含代码:“deDE”时启用对德语语言的支持,但相应的 date-fns 包只是“de”。另一方面英语的手 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)]),
}));
Run Code Online (Sandbox Code Playgroud)
不幸的是我收到打字稿错误:
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)]
Run Code Online (Sandbox Code Playgroud)
它失败并出现相同的错误,即使这样:
dateFnsLocale: dateFnsLocales['pl']
Run Code Online (Sandbox Code Playgroud)
工作得很好。