Deliver a JSON object using a TypeScript function

Recently, I came across TypeScript and decided to convert my current JavaScript code to TypeScript.

In one of my functions, I extract information from a string (data), store it in a JSON object (json), and then return the object. However, when working with TypeScript and not specifying a return type, an error pops up in Eclipse:

No best common type exists among return expressions

Adding the any return type makes the error disappear, but I feel like this is too general of a solution. I've searched for a specific "json" or "object" type without success.

So my question is: what should be the appropriate return type for this function?

Below is the function in question:

function formDataFormatter(data: string) { // or (data: string): any
    // final json object
    var json = {
        y: {
            "vars": [],
            "smps": [],
            "data": []
        }
    };

    // ...
    // processing data...
    // ...

    // populate new variables in JSON (values are placeholders)
    json.y.data = ["data"];
    json.y.smps = ["smps"];
    json.y.vars = ["vars"];

    return json;
};

Answer №1

If you want to specify that you are returning an object (new feature in TypeScript 2.2), you can create a type for your return value:

type MyReturnTypeItem = {
    vars: string[];
    smps: string[];
    data: string[];
}

type MyReturnType = {
    [name: string]: MyReturnTypeItem;
}

function formatData(data: string): MyReturnType {
    var json = {
        y: {
            "vars": [],
            "smps": [],
            "data": []
        }
    };

    // populate JSON with dummy values
    json.y.data = ["data"];
    json.y.smps = ["smps"];
    json.y.vars = ["vars"];

    return json;

};

You can also achieve the same using interfaces instead of type aliases:

interface MyReturnTypeItem {
    vars: string[];
    smps: string[];
    data: string[];
}

interface MyReturnType {
    [name: string]: MyReturnTypeItem;
}

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

What is the process to set up a WebSocket on Tornado for a production server rather than on a local machine?

Recently, I've delved into the world of WebSockets but have only experimented with them in a localhost environment while developing locally. Following this informative tutorial on real-time data visualization: https://medium.com/@benjaminmbrown/real-t ...

Modifying an image in a particular row of a table generated using the *ngFor loop in Angular

Currently, I am working on a table generated by ngFor. Each row in the table contains a button with an image as its background: <tbody> <tr *ngFor='let movie of movies let i = index'> <td>...some values here. ...

"Extra loader required to manage output from these loaders." error encountered in React and Typescript

After successfully writing package 1 in Typescript and running mocha tests, I confidently pushed the code to a git provider. I then proceeded to pull the code via npm into package 2. However, when attempting to run React with Typescript on package 2, I enc ...

Stop images from being stored in the database instead of text characters

Using a proxy, I attempt to parse some HTML. One of the elements is retrieved using jQuery: var site = 'http://www.kartabu.com/pl/index.php?filter=random' var url = 'http://localhost/taboo.blue-world.pl/admin/proxy.php?url=' + encodeUR ...

Is it possible to align the radio-button label above the radio-button in Angular Material 2?

Currently, I am utilizing angular material 2 (material.io) and attempting to position the label of the md-radio-button above the radio button itself. Here's an illustration: View Radio Buttons The official documentation mentions that you can easily ...

Using the variable name instead of inputting the true value

I'm working on a query that extracts data from a JSON field in a Redshift DB. I want to make it more dynamic by using a variable instead of specifying the actual argument each time. For example, rather than hard-coding 'person1' into the que ...

Is there a way to delay the start of this until a legitimate answer is provided in a pop-up window?

Is it possible to delay the loading of this content until a prompt box is answered with a valid response, and have it only appear once a month? Do I need anything beyond JS and HTML for this functionality? <script language="javascript"> function ...

Struggling with the nested array of objects

I have utilized Mongodb aggregation and used the $facet operator to count each value of "reli" and "prov" from the collection. Here is the code I used to retrieve results from the database: const keyy = await db.aggregate([ $facet: { "reli": [ { $group ...

What is the best way to combine a function parameter with various strings and variables in JavaScript?

Here's what the function requires: create_thumbnail($path, $save, $width, $height); I am trying to pass a dynamically generated $path that consists of two variables, $i and $p. This is the code I have been working on: create_thumbnail('images ...

POSTMAN requests are being rejected by the Express API

I've been working on creating an API for a MEAN stack application that handles user registration and authentication. However, I've run into a strange issue where the API is not responding to any requests made through Postman, not even a simple &a ...

Adjust the href attribute of a link dynamically using the value input from a text field immediately

Is there a way to dynamically change the href attribute of a link when a user types in an input field? And is it possible to detect when a user pastes content into the input field as well? Would appreciate any suggestions on how to accomplish this using j ...

I am having trouble getting text to display properly in a jQuery Mobile dialog

I am attempting to dynamically set the header and button texts using JavaScript, but unfortunately it's not working as expected. To demonstrate the issue, I have added my code on jsfiddle: http://jsfiddle.net/tMKD3/8/. Here is the HTML code: <bod ...

Dealing with errors while managing asynchronous middleware in Express

I have implemented an asynchronous middleware in express to utilize await for a cleaner code structure. const express = require('express'); const app = express(); app.use(async(req, res, next) => { await authenticate(req); next(); }) ...

Explore the next page on the API response by navigating to another page

In my next app, I have a versatile function called postAPI, which is used to send requests to the backend server. import Router from 'next/router'; export const postAPI = async ( endpoint, data = {}, headers = {}, method = 'POST&apos ...

Adding data to an array using jQuery

I have a list of items called data and an empty array called quotations: var data = {}; var quotations = []; My goal is to populate the quotations array with data values. Each time I add new data, it is successfully added, but all data values end u ...

Python dialog pop-up application

Looking for some assistance.. I'm aiming to create a Python program utilizing tkinter to display a message box. After closing the initial message box, I'd like two more boxes to appear. Subsequently, upon closing those two boxes, four more shoul ...

Selecting items with checkboxes in a Bootstrap dropdown menu

As I work on customizing a bootstrap dropdown with checkboxes, my goal is to have the label name written on the input dropdown in between ';' whenever a checkbox from the dropdown is selected. This will create a similar result as shown in the upl ...

A guide to successfully transferring textarea content to the clipboard in an Angular application

I'm struggling with a task in an Angular 7 application where I have a textarea and need to copy its content to the clipboard when a button is clicked. I've implemented the following code in the button's click handler: if (this.txtConfigFile ...

Is there a way to eliminate the line that appears during TypeScript compilation of a RequireJS module which reads: Object.defineProperty(exports, "__esModule", { value: true });?

Here is the structure of my tsconfig.json file: { "compileOnSave": true, "compilerOptions": { "module": "amd", "noImplicitAny": false, "removeComments": false, "preserveConstEnums": true, "strictNullChecks": ...

Synchronization problem encountered in an Angular app involving playwright

Currently, I am working on automating a process where the service queries the database and displays the data on the user interface. However, the rendering takes a considerable amount of time, around 3 minutes. Despite using Playwright for automation, it do ...