I have an app that receives a list of supported locales from the backend as a following response:
{locales: [{code: 'enUS'}, {code: 'deDE'}, {code: 'arAR'}]}
I want to use date-fns
library for handling date formatting but I have to import the whole date-fns/locale as I can't know beforehand which locale will be needed:
import * as dateFnsLocales from 'date-fns/locale';
The problem is, some of the locales are in different code format (for example, support for deutsch language is enabled when the backend response includes code: 'deDE', but the corresponding date-fns package is just 'de'. On the other hand date-fns package for english is 'enUS', not just 'en'.
Easy solution imho would be to handle it with some coalescing operator. The example is following:
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)]),
}));
Unfortunately I get the typescript error:
No index signature with a parameter of type 'string' was found on type 'typeof import("date-fns/locale")'. TS7053
Even if I hardcode the attempt like so:
dateFnsLocale: dateFnsLocales['plPL'.substring(0,2)]
it fails with the same error, even though this:
dateFnsLocale: dateFnsLocales['pl']
works just fine.
Object.entries(locales).find(([key]) => key === str)?.[1]
, wherestr
could be your'plPL'.substring(0,2)
for example. (I came across this question trying to find an alternative for theimport * as dateFnsLocales from 'date-fns/locale';
, since it almost doubles the bundle-size in our Angular project..) – Salvucciimport *
always bugged me there – Zamboanga