The correct method to effectively type out a JSON object

Recently, I came across an article on that mentioned the possibility of importing JSON objects into a TypeScript project. Intrigued, I decided to give it a try by importing the following JSON:

{
  "defaultLanguage": "en",
  "languageMap": {
    "en": "English",
    "pl": "Polish",
    "de": "German"
  }
}

To ensure that future changes to this JSON file do not break my application, I created an interface for the imported object:

export default interface IConfig {
  defaultLanguage: string;
  languageMap: ILanguage
}

interface ILanguage {
  [language: string]: string
}

I then proceeded to update the typings.d.ts file:

declare module "*.json" {
  const value: any;
  export default value;
}

Next, I imported the JSON file into my Angular component:

import IConfig from './IConfig';          // Attempted to use IConfig as a type in various places.
import * as config from './config.json';
(...)
private languageMap = config.languageMap; // At this point, Visual Studio Code flagged 'languageMap' with the error:
                                          // [ts] Property 'languageMap' does not exist on type 'typeof "*.json"'.

[ts] Property 'languageMap' does not exist on type 'typeof "*.json"'.

Additionally, the following error popped up:

any

Is there a way to avoid using (<any>config).languageMap and instead utilize my IConfig interface, as suggested in the aforementioned link?

Answer №1

The custom module *.json defines a placeholder module that will identify any file with the extension json and will classify the values within as any. For a more precise definition, consider creating a specialized module for config.json.

To provide a description of the JSON structure, you can create a config.json.d.ts file alongside the main config.json:

//config.json.d.ts
interface IConfig {
    defaultLanguage: string;
    languageMap: ILanguage
}

interface ILanguage {
    [language: string]: string
}
declare const values: IConfig;
export = values;

// usage.ts
import * as configuration from './config.json';

var languageMapping = configuration.defaultLanguage; // All good

If your module system does not support export=value, you can utilize these definitions instead:

//config.json.d.ts
export let defaultLanguage: string;
export let languageMap: ILanguage

interface ILanguage {
    [language: string]: 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

How can I change the CSS class of my navbar component in Angular 2 from a different component?

Here is a custom progress bar component I created: @Component ({ selector: 'progress-bar', templateUrl: './progress-bar.component.html', styleUrls: ['./progress-bar.component.css'] }) export class ProgressBarComponent ...

Tips on utilizing a shell script to pipe JSON data into curl for sending a message to Slack

Are you looking for a way to use the monitor API (e.g. www.example.com/monitor) to retrieve system status in JSON format, such as: { "foo" : 1000, "bar" : 100 } If you want to fetch this system status using curl and send it to Slack, here is a samp ...

Utilize Node to fetch and restrict AWS IP ranges

Have you noticed that AWS releases a json file containing all their IP ranges? You can find it here (Actual JSON HERE) I am considering using this json file to cross-reference against every incoming connection in my node application. However, I'm con ...

"Integrating JSON into a standalone executable using PyInstaller: A step-by-step

Attempting to create the specs.spec file in order to include a JSON file within the executable. block_cipher = None added_files = [ ( 'configREs.json', '.'), # Retrieves the json file from ...

Guide on extracting the keys from an object_construct and displaying them in their own distinct column

My data is structured in a table format. Here is an example: ID ALL_ATTRIBUTES ALL_FIELDS 1 {"name" : "JESSICA"} {"name"} 2 {"age": 15, "name": "JOSH"} {"age", "name" ...

Enhancing Security with Spring and JSON Authentication

I have a Spring/Spring-MVC application that relies solely on JSON for communication. I am now facing the challenge of authenticating my application with Spring Security 3, which utilizes LdapAuthenticationProvider, via JSON. The default Spring Security su ...

Every instance of 'WeakMap' must include the same type parameters

While developing an Ionic App, I encountered a strange issue. Everything was running smoothly until I cloned the source code to a different machine, which resulted in an error that is displayed in the attached image. Even though there are no compilation e ...

Android code to mimic GPS functionality

I need some assistance with coding for my project that merges Android with a web application. Specifically, I want to send GPS coordinates from the Android phone to the web application in order to display the location. I am not well-versed in Android cod ...

Solutions for addressing errors while parsing a JSON file in Python version 3.7

The data in my JSON file is as follows: {"_id": "bc903ddd-90dd-4bff-b711-97dee4cce13c", ... My error occurred in the file "/mnt/c/python/job2/grader/src/streamers.py", specifically at line 417 within the function stdin_reader ...

Delete one item from a group of objects[]

In my TypeScript code, I have a declared object like this: public profileDataSource: { Value: string, Key: number }[]; This results in an object structure that looks similar to the following: 0: Object {Value: "<Select Profile>", Key: null} ...

How can I effectively utilize the Metamask SDK with TypeScript?

Currently, I am in the process of developing a webpack+pnpm+typescript+react website. All the versions being used are LTS and my preferred IDE is VSCode. According to the guide provided by Metamask here, it seems like I need to follow these steps: npm i @m ...

When passing an object to a function inside a promise.then, Typescript may generate an error indicating that the object could

Snippet of code below is extracted from a request controller function. Goal The aim was to generate various notifications based on the paths that are modified. let farmerToUpdate = await FarmerModel.findById(farmerId) if (!farmerToUpdate) throw new cont ...

The TypeScript alternative to Axios request with native fetch functionality

I have a function that sends a JWT validation request: const sendValidateJWTRequestFetch = (url: string, token: string) => fetch(url, { method: 'GET', mode: 'cors', headers: { Authorization: token, 'Ac ...

Using JSON data to render images onto a canvas

I am encountering an issue with a JSON array that I'm receiving from PHP. The array is indexed and has the following format (larger in real scenario) [ [ [17, 28, 1, "z"], [28, 31, 6, "b"], [8, 29, 6, "b"] ...

Decoding JSON with Single Quotes in Swift

Encountering an issue parsing JSON that contains single quotes. Utilizing JSONDecoder for this operation. The API response is provided below and I am seeking a workaround without the need for replacing or regex operations. Any suggestions? "{\&ap ...

Retrieving information from a JSON file using AngularJS

Hello, I am a beginner in Angularjs and I am facing an issue while trying to retrieve data from a JSON file. The output I am getting is quite strange. Below are snippets from my controller.js and services.js files: angular .module('app') .contro ...

The Type {children: Element; } is distinct and does not share any properties with type IntrinsicAttributes

I am encountering an issue in my React application where I am unable to nest components within other components. The error is occurring in both the Header component and the Search component. Specifically, I am receiving the following error in the Header co ...

Receive notifications when there are modifications in the JSON data using AJAX and jQuery

Below is the code snippet I created: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>Sample JSON Data Update</title> </head> <body> <style> span { font ...

When it comes to implementing Ajax and Json in Ruby on Rails, the action url can sometimes be a

Apologies for any language issues. I am wondering about using "get" in JQuery when the url is an action reachable from the browser. In my js file: $.get('/user').success(function(data) { availableTags = data;} ); This is my controller: class U ...

Retrieve all the characteristics accessible of a particular course

I am facing a situation where I have the following class structure: class A { id: number propertyA: string constructor(id: number) { this.id = id } } let a = new A(3) console.log(SomeFunction(a)) // expected output = ['id', ' ...