What strategies can be utilized to extract the structure of JSON files imported via a TypeScript asynchronous function?

Examining the example below:

export type AppMessages = Awaited<ReturnType<typeof loadMessages>>;

export type Locale = "en" | "fr" | "es";

export const loadMessages = async (locale: Locale) => ({
  foo: locale === 'en' 
    ? (await import('../../messages/en/foo.json')).default 
    : (await import(`../../messages/${locale}/foo.json`)).default
});

All JSON files have a consistent structure, but the AppMessages type is resolved as

type AppMessages = {
    foo: any;
}

A potential solution proposed is:

export type AppMessages = Awaited<ReturnType<typeof loadDefaultMessages>>;

export type Locale = "en" | "fr" | "es";

const loadDefaultMessages = async () => ({
  foo: (await import("../../messages/en/foo.json")).default,
});

const loadLocaleMessages = async (locale: Locale): Promise<AppMessages> => ({
  foo: (await import(`../../messages/${locale}/foo.json`)).default,
});

export const loadMessages = async (locale: AppLanguages) =>
  locale === "en"
    ? await loadDefaultMessages()
    : await loadLocaleMessages(locale);

The above solution shapes the AppMessages type correctly, but it may lead to repetition and possible code duplication.

Is there a more efficient approach that achieves the same outcome of having AppMessages shaped based on the JSON data files? Setting the AppMessages type manually is not an option.

Answer №1

It is your responsibility to ensure that all the foo.json files in those directories maintain the same structure as the one located in the /en/ directory. This information needs to be communicated to TypeScript:

type FooMessages = (typeof import("../../messages/en/foo.json"))["default"];

Afterward,

export type AppMessages = { foo: FooMessages; }

export type Locale = "en" | "fr" | "es";

export async function loadMessages(locale: Locale): Promise<AppMessages> {
  return {
    foo: (await import(`../../messages/${locale}/foo.json`)).default,
  };
}

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

Steps for setting up type-graphql in your projectNeed help with

Trying to include this in my TypeScript project: import { ID } from "type-graphql"; Encountered an issue when attempting to install type-graphql. Received a 404 error stating that it could not be found in the npm registry. npm install @types/type-graphq ...

Updating the Nuxt3 editing page with useFetch and $fetch for fetching data, along with a typed storage object that prevents loading issues

My journey with nuxt3 is still new. I am currently working on developing a new API-based app with nuxt3. Previous versions seemed to work "somehow," but they did not meet my expectations. Here are the things I am looking to cover, both in theory and in cod ...

Modifying the return type of an observable using the map operator

I have been investigating how to modify the return type of an Observable. My current framework is Angular 5. Let's take a look at this example: public fetchButterflyData(): Observable<Butterfly[]> { return http.get<Larva[]>('u ...

Announce enhancements to a Typescript library

Utilizing Sequency's extendSequence() feature to enhance all Sequence instances with a custom method: import Sequence, { extendSequence, isSequence } from 'sequency' import equal from '@wry/equality' class SequencyExtensions { e ...

What is the best way to transform a string into emojis using TypeScript or JavaScript?

Looking to convert emoji from string in typescript to display emoji in html. Here is a snippet of the Typescript file: export class Example { emoji:any; function(){ this.emoji = ":joy:" } } In an HTML file, I would like it to dis ...

The type 'function that takes in a CustomEvent and returns void' cannot be assigned to a parameter of type 'EventListenerOrEventListenerObject'

When I upgraded from TypeScript version 2.5.3 to 2.6.1, my custom event setup started giving me an error. window.addEventListener('OnRewards', (e: CustomEvent) => { // my code here }) [ts] Argument of type '(e: CustomEvent) => ...

What is the best way to interpret the data from forkjoin map?

As a newcomer to angular and rxjs, I am seeking guidance on how to properly retrieve data from forkJoin using a map function. ngOnInit(): void { this.serviceData.currentService.subscribe(service => this.serviceFam.getAllFamilles().pipe( ...

ngOnInit unable to properly listen to event stream

I've been trying to solve a persistent issue without success. The problem involves the interaction between three key elements: the HeaderComponent, TabChangingService, and TabsComponent. Within the HeaderComponent, there are three buttons, each with a ...

What are some strategies for enhancing TypeScript/Node speed in VSCode with the help of WSL2 and Docker?

My development environment consists of VSCode running on Windows (v1.58.2) with the Remote WSL extension (v0.58.2). I have Docker Desktop (3.5.2, engine: 20.10.7) set up to work with Linux containers through the WSL2 backend. Within these containers, I a ...

TypeScript and Express create a powerful array combination capability within the type system

After defining the EventType as either "TYPE A" or "TYPE B", I am looking to create a type for an array that can only contain one or both of these event types. Simply typing it as an EventType[] allows duplicates, which is not ideal. type Test = EventType ...

Troubleshooting Problem with Installing Angular2-Google-Maps Component in FountainJS Application

Using the FountainJS Angular2 generator with Typescript and Systems.js has been helpful for scaffolding my project. Check it out here However, I encountered an issue while trying to add a component to the project. Upon importing {GOOGLE_MAPS_DIRECTIVES}, ...

A guide on capturing the response in the POST method within Angular 7

I'm currently working with Angular 7 and I need a way to know if the data has been successfully saved or not. Within my web service code, I have designated "Success" as the status when data is saved correctly, and "Unsuccessful" if the data is not sa ...

What is the issue with this asynchronous function?

async getListOfFiles(){ if(this.service.wd == '') { await getBasic((this.service.wd)); } else { await getBasic(('/'+this.service.wd)); } this.files = await JSON.parse(localStorage.getItem('FILENAMES')); var ...

TypeScript is unable to identify import paths

Currently facing an issue with a specific error in my development environment. I am working with React, TypeScript, and node.js using VSCode on a Mac. I can't pinpoint exactly when this error started occurring. Despite the existence of the file route ...

The struggle of implementing useReducer and Context in TypeScript: A type error saga

Currently attempting to implement Auth using useReducer and Context in a React application, but encountering a type error with the following code snippet: <UserDispatchContext.Provider value={dispatch}> The error message reads as follows: Type &apos ...

An error occurred while defining props due to a parsing issue with the prop type. The unexpected token was encountered. Perhaps you meant to use `{`}` or `}`?

const dataProps = defineProps({ selectedData: <Record<string, string>> }); Under the closing bracket, there is a red line indicating: Error: Unexpected token. Consider using {'}'} or &rbrace; instead?eslint Expression expecte ...

Developing UIs in React that change dynamically according to the radio button chosen

Problem Statement I am currently developing a web application feature that computes the heat insulation factor for a specific area. You can view the live demonstration on Codesandbox <a href="https://codesandbox.io/p/github/cloudmako09/btu-calc/main?im ...

Change number-type object fields to string representation

I am in the process of creating a function that takes an object as input and converts all number fields within that object to strings. My goal is for TypeScript to accurately infer the resulting object's fields and types, while also handling nested st ...

AngularJS 2: Modifications to templates or components do not automatically reflect in the user interface

My background is in Angular 1, where everything worked seamlessly. However, I am encountering serious issues trying to create a basic application using Angular 2 in Visual Studio. After carefully following the "5 minute tutorial" and getting it to work, I ...

How the addition of a type union allows it to be assigned to AnyAction

Struggling with Redux code, I've encountered a peculiar behavior regarding type assignment that has left me puzzled. In the following code snippet, it's clear that you cannot assign anyaction to iaction. Yet, surprisingly, assigning anyaction to ...