Analyzing the object for interface compatibility

When I receive a query string in one of my REST endpoints using koa-router, each value of the query string object parameter is always a string:

{
  count: "120",
  result: "true",
  text: "ok"
}

Within my codebase, I have an Interface that represents the query string object:

interface Params {
  count: number;
  result: boolean;
  text: string;
}

I aim to convert the query string object so that all values match this interface. What are the best practices for accomplishing this?

Answer №1

It's unusual to receive numbers and booleans as strings, given that JSON allows unquoted values for both numeric and boolean data types.

The JSON.parse() method includes an optional reviver callback parameter, which you can utilize within a request interceptor to standardize string representations of numbers and booleans before they reach your interface.

const data = `{
  "count": "120",
  "resut": "false",
  "text": "ok"
}`

const reviver = (key, value) => {
   if(typeof value === 'string' && !isNaN(value)){
       return Number(value)
   }else if(value === 'true' || value === 'false'){
       return value === 'true' ? true : false;
   }   
   return value;
}

console.log(JSON.parse(data, reviver ))

Answer №2

To ensure the input aligns with the expected interface, it is important to convert each property to the correct type.

function convertInputToParams(input:any) : Params {
    var obj = typeof input === "string" 
            ? JSON.parse(input) 
            : input;
    obj.count = +obj.count;
    obj.result = obj.result === "true" ? true : false;
    return obj as Params;
}

An alternative approach would be to create a default instance of Params with predefined properties, then iterate over them to verify that each property in the converted object matches the expected type.

function convertInputToInterface(example:any, input:any) {
    Object.keys(example).forEach(function(key,index) {
        if (!input[key]) return;
        let exampleType = typeof example[key];
        let inputType = typeof input[key];
        if (exampleType !== inputType) {
            if (exampleType == "string") input[key] = input[key] + "";
            if (exampleType == "number") input[key] = +input[key];
            if (exampleType == "boolean") input[key] = input[key] === "true" ? true : false;
            // Handle other cases as needed
        }
    });
    return input;
}

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

There are no specified operations outlined in the Node.js Express documentation

swagger ui https://i.stack.imgur.com/UIavC.png I've been struggling to resolve this issue where the /swagger endpoint seems to only partially read the swagger.json file. Despite configuring everything correctly, no errors are appearing. It simply dis ...

The value returned is undefined when using getStaticProps

Recently, while working on my project with Next.js, I encountered an issue where I was trying to access data but kept getting undefined. Below is the code snippet that I was working with: function Home({books}) { console.log(books) return <div>Home ...

React useEffect alert: Exceeding maximum update depth limit. Any solutions to bypass this issue?

In the code snippet below, I am utilizing the useEffect hook to monitor changes to a percentage variable and then initiating a timer to increment that variable every second. This process starts as soon as the page loads. The percentage variable is crucial ...

How to enhance and expand Material-UI components

I am trying to enhance the Tab component using ES6 class in this way: import React from "react"; import {Tab} from "material-ui"; class CustomTab extends Tab { constructor(props){ super(props); } render(){ return super.rende ...

What is the best way to change the orientation of a vector map?

Is there a straightforward method for rotating a vector-based map on CANVAS in order to integrate it into a browser navigation system? ...

Unable to access member function of Typescript class

I recently started using typescript and encountered an issue while working on a problem. I initially created the following class: export class ModuleInfoContainer extends Array<ModuleInfo> { constructor() { super(); } search(id: number) { ...

arranging <li> elements in alphabetical order

I'm looking for a way to alphabetically sort an unordered list while still keeping the outer html intact. My current method sorts the list alphabetically, but it only reorganizes the inner html of the list elements and not the entire element itself. T ...

Looking to update the URL from another component?

My current project is using Angular 6 and I am working on creating a list of buttons on the left panel such as "Ice cream", "Pop corns", and more. The goal is for users to click on these buttons which will then change the URL of the add button located in t ...

Tips for duplicating specific div elements

Is there a way to create copies of selected divs within the same panel using a Javascript report designer? I attempted to achieve this by using the following code snippet: function DesignerClone() { $(".ui-selected").each(function () { va ...

Utilizing HTML5 Canvas for Shadow Effects with Gradients

Surprisingly, it seems that the canvas API does not support applying gradients to shadows in the way we expect: var grad = ctx.createLinearGradient(fromX, fromY, toX, toY); grad.addColorStop(0, "red"); grad.addColorStop(1, "blue"); ctx.strokeStyle = gra ...

Is JavaScript's setTimeout 0 feature delaying the rendering of the page?

Based on information from this StackOverflow post The process of changing the DOM occurs synchronously, while rendering the DOM actually takes place after the JavaScript stack has cleared. Furthermore, according to this document from Google, a screen r ...

What sets apart Object.assign {} from Object.assign []?

While reviewing code done by a previous developer who is no longer with us, I observed that they sometimes used Object.assign({}, xyz) and other times they used Object.assign([], abc); Could there be a distinction between the two methods? ...

Two Ajax Requests Simultaneously

I am currently faced with the challenge of handling two requests simultaneously. The first request involves executing a lengthy PHP script that takes 10 minutes to complete (I cannot modify it using JavaScript, so that's not an option). The second ...

Retrieve a JavaScript file located in a separate folder

I'm facing an issue with a project that has the following layout: project | - public | - -index.html src | - -index.js The code I am using to import the file is as follows: <script src="../src/index.js"></script> H ...

What is the best way to utilize typed variables as types with identical names in Typescript?

Utilizing THREE.js with Typescript allows you to use identical names for types and code. For instance: import * as THREE from '/build/three.module.js' // The following line employs THREE.Scene as type and code const scene: THREE.Scene = new THRE ...

Stacked column tooltip displaying an array of 3 values

I am working with a json code that looks like this: [[1385420403000,9.86,6.91],[1385506802000,11.89,6.57],[1385593203000,14.11,10.58],[1385679602000,9.1,8.9],[1385766003000,13.59,7.53],[1385852402000,10.68,6.69],[1385938803000,11.03,10.52],[1386025202000, ...

Output object data to table by clicking on it - requires two clicks for the data to be

I have a situation where I want the user to click a button in order to print an object obtained from a web service into a table. The issue is that currently, I have to click the button twice for it to work properly. Here's some more detail: The button ...

View real-time data in Vuejs 3 as it executes

I am currently working on a form that populates a table with data retrieved from a Laravel API. I am using Vue.js 3 and Composition API to build my entire application. When the button is clicked, I want the table to be filled with data from the form. The b ...

What is the best way to evaluate a sequence of actions and their outcomes?

Recently, I've dived into the world of writing automated tests for a React application. Along the way, I encountered some intriguing questions about the best approach to testing a series of interactions within the app. Let's imagine a scenario w ...

Utilize a Python script to transmit data to JavaScript through JSON in order to dynamically alter the content of

Currently, I am developing an interactive display that utilizes sensors on a raspberry pi. The display is set to show a webpage and I have implemented a python script to handle sensor interaction. My goal is to change the displayed web page when a user p ...