Encountering an import error when trying to dynamically import date-fns/locale libraries in TypeScript

My application receives a list of supported locales from the backend in the following response:

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

I plan to utilize the date-fns library for date formatting, but I need to import the entire date-fns/locale as I cannot predict which locale will be required in advance:

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

The issue arises when some locales use different code formats. For example, German language support is indicated by 'deDE' in the backend response, but the corresponding date-fns package uses just 'de'. Conversely, the English package is 'enUS', not just 'en'.

An easy solution would involve using a coalescing operator. Here's an example:

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

However, I encounter a TypeScript error:

No index signature with a parameter of type 'string' was found on type 'typeof import("date-fns/locale")'. TS7053

Even if I try hardcoded attempts like:

dateFnsLocale: dateFnsLocales['plPL'.substring(0,2)]

it still fails with the same error, despite this working fine:

dateFnsLocale: dateFnsLocales['pl']

This challenge requires further exploration for resolution.

Answer №1

Below is the script I have implemented to perform dynamic lookups using Expo's Localization module.

import * as Localization from 'expo-localization';
import * as Locales from 'date-fns/locale';
import { Locale } from 'date-fns';

/**
 * Function to retrieve a date-fns locale based on a given Expo localization.
 * This function defaults to `en-US` if no matching locale is found.
 * @param localization: The Expo Localization object containing the locale and region.
 * @returns The corresponding 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
  );
}

Test case:

import { enUS, fr, frCA } from 'date-fns/locale';

describe('Testing Date-fns Locale Lookup', () => {
  it('Should find "fr"', () => {
    expect(getDateFnsLocale({ locale: 'fr', region: null })).toBe(fr);
  });
  it('Should find "fr-CA"', () => {
    expect(getDateFnsLocale({ locale: 'fr-CA', region: 'CA' })).toBe(frCA);
  });
  it('Should not find "zz-ZZ"', () => {
    expect(getDateFnsLocale({ locale: 'zz-ZZ', region: 'ZZ' })).toBe(enUS);
  });
});

Answer №2

Here is the solution I came up with:

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

export const getDateFnsLocaleByActiveLanguage = (lang: string) => 
  lang === 'en'
   ? loc['enUS']
   : Object.values(loc).find((l) => l.code === lang);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Assign a value to a cookie using Node.js

I'm currently working on a web project using node.js and express. What is the best way to establish a cookie value? ...

Vue Basic Components 'T' has not been declared

After updating to Vue 3.4.30, I encountered an issue while trying to use Generic components. When attempting to use T as a type for a property, I received an error message. Any guidance or suggestions on how to resolve this would be greatly appreciated. I ...

Encountering an error while trying to import GraphQL resolvers and schema

Upon attempting to start the server with the following setup, an error is encountered: Error: "createUser" defined in resolvers, but has an invalid value "function (userInput) {... The resolver's value must be of type object. index.ts const schema ...

The error message [jsonFlickrApi is not defined] in JavaScript is indicating that the

Upon calling a FLickrAPI, the returned xmlhttp.responseText appears as follows: jsonFlickrApi({"photos":{"page":1, "pages":200, "perpage":100, "total":"19934", "photo":[{"id":"7315581986", "owner":"62691288@N00", "secret":"504915125a", "server":"7090", ...

Utilize Javascript to locate the image width and assign it to the wrapper divs in WordPress

I am trying to figure out how to set the wrapper divs' widths equal to the size of the images (featured images) they contain so that they are evenly spaced from each other. I came across a potential solution here: (solution at the bottom), but I am ...

Utilizing Loopback Callbacks within a Looping Structure

While working in a for-loop, I encountered an issue where I needed to access the loop variable 'i' from within a callback function but it was not accessible due to closure restrictions. Despite attempting different methods such as using (i) or ca ...

Using pure JavaScript to trigger a pop-up window upon submitting a form

Struggling with sending form data to a PHP page using radio buttons for poll results display. No luck with passing variables using $_POST or $_GET methods. I've checked both, but still nothing. When I tried printing the arrays on the PHP page: <? ...

Transferring information between Vue.js components via data emissions

Greetings from my VueJS Table component! <b-table class="table table-striped" id="my-table" :items="items" :per-page="perPage" :current-page="currentPage" :fields="fields" @row-clicked="test" lg >< ...

Having trouble interacting with an SVG path element in Selenium WebDriver

Currently, I am working on the automation of chart data and here is how the data is displayed. <g style="cursor:pointer;" clip-path="url(#highcharts-2)" transform="translate(62,10) scale(1 1)" class="highcharts-markers highcharts-series-0 highcharts-tr ...

Navigate to the editing page with Thymeleaf in the spring framework, where the model attribute is passed

My goal is to redirect the request to the edit page if the server response status is failed. The updated code below provides more clarity with changed variable names and IDs for security reasons. Controller: @Controller @RequestMapping("abc") public clas ...

Unable to display nested objects retrieved from a JSON API in Angular

How can I retrieve images from an API and properly access the specific object within the object? Any tips would be greatly appreciated! API Endpoint: This is how my interface is structured: export interface MovieModel { id: number; name: string; ...

Are you ensuring compliance with licensing in your Webpack bundles?

Can webpack be used to verify license compliance? I'm looking for a way to ensure that the license headers from all modules built by webpack are included in the final output file. How can we confirm this is happening? Furthermore, I am also intereste ...

Dynamically add new values or create interfaces in Typescript on the fly

I am working with an Angular Material Table and I have created an interface that serves as the dataSource for the table. However, I am facing a challenge because the data coming from the backend is unknown. Is there a way to dynamically add a new value to ...

Ways to turn off debugging for `ts` source maps

I need help troubleshooting a TS project. When using WebStorm, it automatically detects source maps and displays the original ts files. I prefer not to use source maps and debug the generated js files instead. How can I turn off the use of source maps in W ...

Modifying multiple heading tags simultaneously with jQuery

Currently utilizing jQuery to append a string to all heading tags (h1, h2,..., h6) and display it on the screen. Seeking guidance specifically for the replacing aspect, and open to solutions using plain javascript as well. The code I have so far, which I ...

Ways to incorporate HTML elements into a forthcoming HTML element (React or JavaScript recommended)

As I work on enhancing the accessibility of some HTML content that is loaded through a third-party application, I find myself faced with the challenge of adding accessible elements to dynamically spawned list items with anchor tags. My attempt to achieve ...

Crafting dynamic parameters in the Express router - A step-by-step guide!

Original Code Example: const express = require('express'); const router = express.Router(); router.get('/data/:d1/:d2/:d3', require('../apifoo').foo); Route: /data/:d1/:d2/:d3 Path: /data/1/2/3 req.params : 'd1' : ...

"Need some tips on how to make the body animate downwards when toggling the

Just starting out and trying to teach myself how to code. I've come across an issue where my Navbar-collapse is now overlapping the content of my page, and this time it's a problem because I want the background of the navbar-collapse to be transp ...

I'm working on separating the functionality to edit and delete entries on my CRM model, but I'm having trouble finding a way to connect these buttons with my data fields

I am encountering some difficulties while trying to implement separate functionality for editing and deleting items on my CRM model. I have already created the necessary API in Angular, but I am struggling to bind these buttons with my field. Any assistanc ...

Steps to extract viewmodel information from a specific controller following an ajax request

I am encountering an issue with passing updated data from my controller to the view after making an Ajax call. Here is a simplified version of what I am trying to achieve: Javascript $ANALYZE = $('#submitID'); $ANALYZE.click(function () { ...