Switch up the data format of a JSON file that is brought into TypeScript

When bringing in a JSON file into a TypeScript project with the resolveJsonModule option activated, the TypeScript compiler can automatically determine the type of the imported JSON file. However, I find this type to be too specific and I would like to replace it with a more generic one. I attempted to achieve this by creating a custom type definitions file:

// Custom type definition file - modules.d.ts

declare module "*.json" {
  const value: Record<string, string>;
  export default value;
}

Unfortunately, the TypeScript compiler seems to be disregarding this definition.

The only workaround that has worked for me is using temporary variables, like so:

import DATA_JSON from "./data.json";

const DATA  = DATA_JSON as Record<string, string>; // Utilizing my own type instead of the inferred one.

export { DATA };

However, this method becomes tedious. Is there an alternate approach to assigning custom types to JSON files imported in TypeScript?

Answer №1

If you're looking to achieve a specific structure or types, consider utilizing mapped types. It may be the right approach for what you need.

This requirement could be a great opportunity to delve into more advanced TypeScript concepts (Check out Matt Pocock on YouTube for some valuable insights).

import DATA_JSON from './data.json';

const OWN_TYPED_DATA_JSON = DATA_JSON as unknown as {
   [key in keyof typeof DATA_JSON]: {
      [nestedKey in keyof typeof DATA_JSON[key]]: {
         [moreNestedKey in keyof typeof DATA_JSON[key][nestedKey]]: string
      }
   }
}

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

Executing TypeDoc on a Windows system results in zero files being created and no error messages reported

I have been working on generating documentation for a JavaScript application using TypeDoc. Unfortunately, I am facing an issue where TypeDoc is not outputting any files or errors. To get started, I installed TypeDoc within the project folder: npm instal ...

The mongoose fails to establish a connection with the Mongo Db Atlas

I am having issues with my simple node express app when trying to connect to MongoDB atlas. Despite deleting node_modules and re-downloading all packages, I am still encountering the same error. The specific error message reads as follows: Cannot read pro ...

Is it possible to include if else logic code within a catch statement?

There's a nagging feeling within me that having logic code within a catch statement is not the right approach. For example, my catch block currently looks like this: try{ // do some stuff that throws some unexpected errors } ...

Obtain data from a single module and incorporate it into a different one

In my Angular 2 application, I am dealing with two component files - home.ts and folder-selector.ts. Within the folder-selector.ts file, there is a variable named pathToNode. I am trying to figure out how to access this value from within the home.ts file ...

Adding an array to a JSON data in C++

If I have two integers 'a' and 'b', I can easily append them to a Value in Json using the following code: Value root; Value v = root["int"]; int a = 1; int b = 2; v.append(a); v.append(b); Resulting in the Json file: "int": [ ...

Populate SQL Server with data retrieved from REST API in XML or JSON format

Greetings and thank you for your help in advance! Can data be retrieved from a script in SQL using REST API calls, either in XML or JSON format, and then inserted into records of a newly created table? To clarify, the API being used is a REST API availab ...

The module ~/assets/images/flags/undefined.png could not be found in the directory

When I use the img tag with a dynamic address filled using require, it works well in the component. However, when I try to write a test for it, an error is thrown. console.error Error: Configuration error: Could not locate module ~/assets/ima ...

Is it possible that Mongodb's aggregate function produces a Circular Json Object, whereas in the shell it only returns a regular

Currently, I am developing a Node.js application that is designed to return an array of random documents. To accomplish this task, I am utilizing the aggregate function from MongoDB along with the $sample operator. When executing a query like db.factslist ...

Transforming a JSON object property value from an array into a string using JavaScript

I am facing an issue with an API call I am using, as it is sending objects with a single property that contains an array value (seen in the keys property in the response below). However, I need to work with nested arrays in order to utilize the outputted v ...

Incorporate the Get Your Guide Widget into an Angular2 component

Currently, I am attempting to embed a "Get Your Guide" Widget within an Angular2 application. Although the script in index.html is being requested successfully, I am facing difficulties adding it to the HTML of the component. <script async defer src=" ...

Bring JSON into Angular 7 application

For my Angular project, I've set up a localization service by importing JSON files. Following this recommended method, I updated my typings.d.ts as shown below: declare module "*.json" { const value: any; export default value; } Everything w ...

What is the proper way to write a function that verifies the presence of a key in an object and then retrieves the associated value?

After holding out for a while hoping to stumble upon the solution, I've decided to give it a shot here on SO since I haven't found it yet. import { PDFViewer, MSViewer } from './viewerclasses' //attempting to incorporate a union of key ...

Is CurrentThread.CurrentCulture disregarded by JavaScriptSerializer in ASP.net MVC?

I am currently investigating whether the JavaScriptSerializer used internally to serialize data to JSON in ASP.net MVC 4 ignores the CultureInfo of the current thread. Here are my observations so far. I have set the culture info properties in the Applica ...

Utilizing external applications within Angular applications

I have the task of creating a user interface for clocker, a CLI-based issue time tracker. Clocker functions as a stand-alone node.js application without any programming interface. To begin tracking time for an issue labeled 123, the command would typically ...

The best method for parsing Twitter JSON data from a single or multiple files and importing it into Python

I am currently facing a challenge with parsing the Twitter dataset, which consists of multiple JSON files. My issue lies in parsing JSON objects to Python using json.loads(), as it only works for one object at a time. I have come across a similar question ...

Troubleshooting Appium error management is ineffective

As a newcomer to appium, I might have made some mistakes. I'm encountering a problem with appium while using wdio and jasmine. it('wtf', (done) => { client.init().element('someName').getText() // ^ here ...

Is condition checking taken into consideration by Typescript?

I keep encountering this strange TypeScript compile warning that just won't go away, even though I believe it shouldn't be there in the first place... Here are the interfaces I'm working with: interface Props { tasks: TaskType[] } inter ...

What is the process for retrieving information from a particular section of a Wikipedia page with the help of the Wikipedia API?

I am currently working on creating an android app and I am in need of extracting the Nutrients section of a specific vegetable or fruit from Wikipedia to display in my app. https://i.sstatic.net/avaGA.png This is my progress so far... I am attempting to ...

Struggling to properly structure WCF JSON data for HighCharts integration?

I am having issues binding my WCF JSON data to HighCharts Pie. When I hardcode the data, it works fine but dynamic data processing does not seem to work. Original from WCF -[{"AllRecordsUrl":"http:\/\/EMS\/sites\/IST\/report.aspx ...

What methods can I employ within an AngularJS controller to retrieve data from Google App Engine instead of solely relying on a JSON file?

As a newcomer to web development, I have been experimenting with retrieving data from a Google App Engine datastore and selectively displaying it on a webpage using AngularJS. While I have successfully integrated Angular with a JSON file and posted the con ...