Ensure the JSON file aligns with the TypeScript Interface

I am working with a config.json file.

{
  "profiler": {
    "port": 8001,
    "profilerCache": {
      "allowedOriginsRegex": ["^http:\/\/localhost:8080$", "i"]
    }
  },
  "database": {
    "uri": "mongodb+srv://...",
    "dbName": "profiler",
    "collectionName": "profiles"
  }
}

During the build process, I need to ensure that the JSON structure matches my defined interface.

export interface Config {
  port: number
  profilerCache: {
    allowedOriginsRegex: [string, string]
  }
  database: {
    uri: string
    dbName: string
    collectionName: string
  }
}

What is the most straightforward way to enforce type safety for my JSON files?

Answer №1

When you assign the JSON object to a variable with an interface type, it will highlight any structural errors present.

export interface Configuration {
  port: number
  profilerCache: {
    allowedOriginsRegex: [string, string]
  }
  database: {
    uri: string
    dbName: string
    collectionName: string
  }
}

let jsonData: Configuration = {
  "port_error": 8001,  // Error: Object literal may only specify known properties, and '"port_error"' does not exist in type 'Configuration'.
  "profilerCache": {
    "allowedOriginsRegex": ["^http:\/\/localhost:8080$", "i"]
  },
  "database": {
    "uri": "mongodb+srv://...",
    "dbName": "profiler",
    "collectionName": "profiles"
  }
}

Check out this Typescript Playground Example for more insight.

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

Embark on a journey through a preorder traversal of a Binary Tree using TypeScript

Hello! I've been tasked with creating a function that iterates over a binary tree and returns all its values in pre-order. Here is the code snippet: interface BinTree { root: number; left?: BinTree; right?: BinTree; }; const TreePreArray ...

python: Loading and organizing JSON data in a pandas dataframe

{ "total_count": 2316913, "incomplete_results": false, "items": [ { "id": 13737149, "name": "gremlins.js", "full_name": "marmelab/gremlins.js", "owner": { "login": "marmelab", "id": 3116319, ...

What is the process for transmitting an ndarray response from a Flask server to a Python client?

I need assistance in sending an ndarray (predictionsIm) of shape (1536, 1536, 3) from a Flask server to a Python client. After researching how to convert predictionsIm (ndarray) to a list and then return the JSON data, I implemented the following: return ...

Is it possible to utilize a function within an Angular [routerLink] to define the query parameter?

When receiving a response from the API without an ID, it presents data fields like url, name, gender, culture, etc. However, I need to create a route to access specific character information using /characters/:id. Since there is no direct ID provided in th ...

Retrieve the index values from an array within a BigQuery data JSON

After importing data from Firestore to BigQuery, I noticed that the format of my data aligns closely with this: data = [ { id: "item1", status: { options: [ { title: "Approved", color: "#00ff00" }, ...

The lack of invocation of Angular 4's ngOnInit function following a call to router

In my Angular application, I have 3 tabs where one tab displays a table listing employees. Initially, everything works well when the data is loaded for the first time in ngOnInit using an HTTP get request. However, after adding a new employee through a for ...

The TypeScript compiler is unable to locate the identifier 'Symbol' during compilation

Upon attempting to compile a ts file, I encountered the following error: node_modules/@types/node/util.d.ts(121,88): error TS2304: Cannot find name 'Symbol'. After some research, I found that this issue could be related to incorrect target or l ...

Transforming JSON data into a CSV format

Dealing with a large JSON file containing multiple individual JSON objects, I am working on converting it to a CSV format where each row represents a combination of the outer id/name/alphabet in a JSON object and one set of conversion: id/name/alphabet. Th ...

How can we leverage Shared and Core modules alongside Feature modules in Angular development?

When developing my Angular application, I have adopted a specific architecture approach and included a shared.module.ts file in the shared folder. While leveraging lazy-loading in my app, I find myself puzzled about the necessary imports, declarations, and ...

Transition your Sequelize migrations to TypeORM

I'm currently in the process of transitioning a Node.js application from vanilla JS to Nest.js. In our previous setup, we used Sequelize as our ORM, but now we've decided to switch to TypeORM for its improved type safety. While exploring the Type ...

The chosen value in AngularJS should not be displayed in other dropdowns loaded from JSON

Seeking assistance with an AngularJS challenge. I'm working on implementing multiple dropdowns using ng-repeat from JSON data. The goal is to ensure that once a value is selected in one dropdown, it should not appear in the others. As someone new to A ...

AngularJS making use of multiple checkboxes to filter data from a nested JSON structure

Hi everyone, I came across a helpful resource on implementing multiple checkboxes filters in AngularJS: angular js multiple checkbox with custom filters I am facing a similar issue but with a multilevel JSON structure. Here is an example of what I am deal ...

How can I utilize npm with the original source code instead of minified or bundled code?

I am looking to access npm and JavaScript (or TypeScript) 3rd party libraries directly from the source code. Similar to how I can make changes in Python libraries by going into their source code, I want to have the same capability with my JavaScript depen ...

What is the proper way to manage the (ion select) OK Button?

Hey there, I'm working with an Ionic select directive and I need to customize the functionality of the 'OK' button. When I click on it, I want it to call a specific function. I'm aware of the (ionChange) event, but that only triggers w ...

Combine Sonarqube coverage with Istanbuljs/NYC for enhanced code analysis

In my typescript project, we utilize a Jenkins pipeline to run all functional tests in parallel after building the main container. Towards the end of the pipeline, we conduct a code coverage check and then transfer the results to sonarqube. Below is an ex ...

The utilization of React.Component inheritance in TypeScript

In my attempt to develop a base class using React.Component and derive two classes from the base class, I have encountered an issue. Here is how I structured the classes: interface BaseItemProps { base_prop: string; } class BaseItem<P, T> exten ...

Gather and consolidate all files into a single file using Node.js / JavaScript

I currently have 3 JSON files located in my project/Folder file1.json { "id":"01", "name":"abc", "subject":[ "subject1":"Maths", "subject2":"Science" ...

Troubleshooting: AngularJS ng-options failing to populate the list of objects

Having trouble populating a combo box in AngularJS. Here is the controller code snippet: var app = angular.module('app'); app.controller('roadmap', function($rootScope, $scope, $http, $q, leFactory) { $rootScope.activityInfoList=[ ...

Developing a typescript React component with a generic callback event handler function passed as a prop

I'm struggling with developing a callback event handler function that can be passed down as a prop to my component. My objective: Allow users to provide a custom callback function that: always accepts the same argument an event (not a react/dom even ...

How can I position ports on the right side of a graph element in JointJS?

I'm in the process of developing an Angular application that allows users to dynamically create graphs. Currently, I am working on a function that adds ports to vertices and I want the user to be able to select the position of the port (right, left, t ...