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

How to handle blank property values in JavaScript objects and convert them to null in an ASP.NET Web API

Hey there! I'm facing an issue where when I post a JavaScript object to an ASP.NET Web API, some property values are blank like the example below: var o={ ID=1, Fname="Tom", Mname="", Lname="Wilson" } However, in the Web ...

Encountering an error while attempting to access a property of a non-object in the

Recently, I have been exploring the world of JSON. After retrieving a JSON object from the database, it appears in this form: Array ( [0] => stdClass Object ( [id] => 1 [data] => {"vehicle":[{"year":"2000","mak ...

I keep encountering the following error message: " ERROR Error Code: 200 Message: Http failure during parsing for http://localhost:3000/login"

My Angular Login component is responsible for passing form data to the OnSubmit method. The goal is to send form data from the front-end application and authenticate users based on matching usernames and passwords in a MySQL database. ***This login form i ...

What is the best way to search for a specific value in the Record definition?

In the documentation for Typescript, a type is defined to be used as keys into a Record<>. It seems like this is done to restrict and secure the keys that can be utilized. type CatName = "miffy" | "boris" | "mordred"; W ...

Sending a $.ajax post request transforming into a get

Struggling to understand the behavior of my jquery ajax request, I've hit a roadblock. function newContact() { $.ajax({ type: 'POST', contentType: 'application/json', // url: ...

Unusual Observable behavior in Angular/Typescript leaves developers scratching their heads

I have encountered an issue with a single Angular 2 service: validate() { return this.http.get('api/validate', data); } Consuming the API works fine: this.ValidationService.validate().subscribe(result => { console.log(&a ...

How can you make sure that a class property in TypeScript always matches the name of the class?

Click here for an example interface ICommandHandler<T> { type: string // how can we ensure that this equals T.name? handle(command: T): void; } interface ICommand {} class CreateTaskCommand implements ICommand{} class CreateTaskCommandHandler ...

`Error importing react-markdown in Next.js 11.1 with TypeScript``

Having trouble with importing react-markdown in my next.js SSG project. When running npm run dev, I encounter an error that prevents me from proceeding to test in next export. I understand that react-markdown is an esm package, but I'm not sure how t ...

Transform JSON object into a structured JSON tree representation

I have the SQL query results stored in JSON format value = [ {"Machine": "Mach 1", "Device": "Dev a", "Identifier": "HMI 1"}, {"Machine": "Mach 1", "Device": & ...

Delegate the custom deserializer in Jackson back to the default one

Is there a strategy in a custom Jackson deserializer to hand over certain properties to the default deserializer for processing? @Override public final T deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { ...

Anticipated the start of an array, but encountered the start of an object at line 1, position 2

I'm currently developing an app that requires sending notifications to specific devices, but I've encountered an error. I'm actively searching for a solution and utilizing the REST API endpoint . It's been a challenge, but I'm dete ...

Enforce directory organization and file naming conventions within a git repository by leveraging eslint

How can I enforce a specific naming structure for folders and subfolders? I not only want to control the styling of the names (kebab, camel), but also the actual names of the folders and files themselves. For example, consider the following paths: ./src/ ...

The "npx prisma db seed" command encountered an issue: Exit code 1 error occurred during the execution of the command: ts-node --compiler-options {"module":"CommonJS"} prisma/seed.ts

this is a sample package.json file when I try to execute the command "npx prisma db seed", I encounter the following error: An error occurred while running the seed command: Error: Command failed with exit code 1: ts-node --compiler-options {&qu ...

Prevent Component Reloading in Angular 4 when revisiting the page

My application consists of three main components: 1) Map 2) Search 3) User Profile Upon logging in, the MAP component is loaded by default. I can navigate to other screens using the header menu link. I am looking to implement a feature where the map comp ...

Getting the URL for a downloaded image using ImageLoad on Android

I encountered an issue with my Android application In the database, I stored URLs of some images and now want to download these images for a viewpager display using ImageLoader. The problem arises when trying to download the image URLs from the server. I ...

Inter-component communication in Angular

I am working with two components: CategoryComponent and CategoryProductComponent, as well as a service called CartegoryService. The CategoryComponent displays a table of categories fetched from the CategoryService. Each row in the table has a button that r ...

Incorporating XMLHttpRequest in my React Typescript App to trigger a Mailchimp API call, allowing users to easily sign up for the newsletter

My website needs to integrate Mailchimp's API in order for users to subscribe to a newsletter by entering their email into a field. I am looking to implement this without relying on any external libraries. To test out the functionality, I have set up ...

What is the best way to provide JSON data instead of HTML in Angular?

Is it possible to output processed data as json instead of html? I want to process backend data and output it as json for a specific url. How can I prepare a component to do this? Currently, the app serves html pages where components process backend data ...

Having trouble retrieving JSON data from an external URL in AngularJS when making a $http.get call and using the success method?

Code in the Controller.js file: let myApp=angular.module('myApp',[]); myApp.controller('myController', function($scope,$http){ $http.get('data.json').success(function(data){ $scope.art=data; }); }); ...

Converting a JSON variable into a clickable hyperlink

I need help with parsing a json variable into another link using the code below. However, I encountered an error that says "file_get_contents(0): failed to open stream: No such file or directory ". The directory is accessible when entered manually. < ...