Is it possible to pass generics into a Promise, such as Promise<T>?

Here's the code snippet for a function I am working with:

class RestService {
    public async get<T>(func: string): Promise<T> {
        var toRet = {};
        await fetch(EndPoint + func)
        .then(response => response.json() as Promise<T>)
        .then(data => {
            toRet = data;
        })
        .catch(e => {
        });

        return toRet as T;
    }
}

Everything is functioning properly except for one issue - the response I receive in 'data' always ends up as a generic object.

Let's say I have a model defined like this:

class Model
{
   string name;
}

and I make a call to the function like this:

get<Model>("getmodel")

The response consistently appears as a generic object structured like:

{name:"some name"}

As far as my knowledge goes, Typescript does support generics and Promise can handle variable types. My assumption is that perhaps passing a generic into another generic is causing this behavior?

Answer №1

Perhaps a more efficient way to express this concept would be to refactor the code in the following manner.

class RestService {
    public async fetchDetails<T>(func: string): Promise<T | void> {
        return await fetch('' + func)
            .then(response => response.json() as Promise<T>)
            .then(data => {
                return data;
            })
            .catch(e => {
            });

    }
}

You can also experiment with it in the playground by clicking on this article might offer valuable insights.

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

Parse through a JSON input and generate a hierarchical treeview structure using the specified keys, while also considering any child keys present

Can someone assist me with the code snippet below? JObject my_obj = JsonConvert.DeserializeObject<JObject>(ReceivedJson); ParseJson(my_obj); //method to store all the nested "keys" and the "id" values public void ParseJson(JObject obj) ...

Using Ansible to handle data that may be in either JSON or YAML format

Currently, my task involves utilizing Ansible to analyze a configuration file that could either be in JSON or YAML format. My objective is to extract specific values from certain nodes within the file. I am aware that I can utilize from_json or from_yaml ...

Iterate through a collection of objects and organize the data in a specific way

Within the data structure of my API response, I am attempting to iterate through an array of objects under the items key. Each value inside these objects needs to be formatted based on the corresponding format type specified in the header key. To assist wi ...

Strategies for handling multiple HTTP error messages in AngularJS: Ensuring usability amidst errors

In developing my Angular 1.5.3 app, I encountered a challenge involving calling two separate endpoints with $http in the main controller of my 'home' page. These endpoints are independent and yield different data sets. The issue arises when both ...

What impact does control flow have on narrowing variable types?

Having reviewed this particular question, my current focus is on understanding how variables can be narrowed down using control flow. An example: type T1 = { a?: { b: string } } const t1: T1 = {} t1.a.b // displays error, possibly undefined t1.a ...

I am having trouble getting my Ajax script to function properly when the datatype is

When working on my codes, I encountered an issue where I could successfully post data without any errors. However, I faced a problem when attempting to retrieve data from a PHP file to display in an HTML tag. If I remove 'dataType: 'json'&ap ...

How does Zone.js enhance the functionality of Angular 2?

I am currently delving into the world of Angular 2.0 and stumbled upon the mysterious file known as Zone.js. I am curious to understand the role of Zone.js and how it can enhance the performance of my application. ...

How can we efficiently assign an array of JSON responses using Observables and map within a TypeScript interface, and then display it in HTML using *ngFor in Angular 2?

export interface Relation{ name: string; address: string; dob: number; } The JSON response I received is as follows: [ {"name":"John", "address":"xyz", "dob":"2000-01-10"}, {"name":"Jamie", "address":"abc", "dob":"1990-01-10"} ] The issue seems to be wi ...

` `Obtaining exclusively NULL values from the get_json_object function in PySpark

In my Spark Dataframe within Palantir Foundry, I have a column named "c_temperature" which contains a JSON string in each row following this schema: {"TempCelsiusEndAvg":"24.33","TempCelsiusEndMax":"null","TempC ...

Creating a redux store with an object using typescript: A step-by-step guide

Having recently started using Redux and Typescript, I'm encountering an error where the store is refusing to accept the reducer when working with objects. let store = createStore(counter); //error on counter Could this be due to an incorrect type set ...

Issue with PHP incorrectly encoding JSON when writing to a file

I encountered a problem while working on this task. I used preg_split in PHP to create an array. However, my challenge now is converting it into JSON format. Despite trying several methods, the resulting code appears poorly written and does not seem to be ...

Securing components in Angular2 with login verification

After wrapping multiple components' ngInit with a check to verify if users are logged in or not, I am looking for a way to avoid repeating the same code. export class ComponentX implements OnInit { constructor(private _authService: AuthService) { ...

What is the process for exporting individual nested values to separate files in MongoDb?

I am facing a situation with this tree structure: Document |--_id: ObjectId(21346f7b7ada873) |--a : "valueA" |--b : "valueb" |--c : | |-- ca : "ca" | |-- cb : "cb" | |-- cc : {...} | |-- cd : [...] | |-- ce : {...} | |-- cf : {...} . . . Suppo ...

Tips for utilizing parameters within SQL Server

Hello everyone! I am new to SQL Server in Azure functions using Typescript. I am currently facing an issue while trying to update a row in the database using declared variables, particularly with VARCHAR types. Strangely, it works fine in the database tool ...

What mysteries lie within an unfamiliar JSON object or Array?

Looking to access a list of friends' names from the Facebook API in an Android app. Wanting to figure out how to read JSON objects and arrays during this process. I have received JSONObject and/or JSONArrays, but I am unsure about their contents. I c ...

Utilize your access token to send a message through Google Business Messages

Currently, I have successfully set up a method to send messages using the Google Business Messages API from an agent to a user through NodeJS. const bmApi = new businessmessages.businessmessages_v1.Businessmessages({}); This process requires authenticatio ...

Creating a Rails partial from JSON data with a custom rake task

Currently, I am utilizing a helper function: def fetch_static_blog_posts Rails.cache.fetch("blog_posts", :expires_in => 30.minutes) do url = URI('http://www.xxxxxxxx.com/blog/?json=get_recent_posts') request = Net::HTTP.get(url) ...

Creating a TypeScript interface that has keys determined by the elements in an array

My goal is to create a function that returns a record with keys specified by a string array. For example: // return type -> { itemA:SomeType,itemB:SomeType } const res = doThing(['itemA', 'itemB']) Do you think this is achievable? ...

I am not forcing the Angular module to conform to my perspective

Hello, I am new to Angular and trying to experiment with some code. However, I seem to be stuck with the app.js file which is throwing an error: Uncaught SyntaxError: Unexpected token . Below is the structure of my application, which I obtained by cloning ...

The type 'string' cannot be assigned to type 'ImageSourcePropType'

Context Attempting to utilize a SVG component in React Native with the xlinkHref property within an Image tag. The SVG file was converted into a React Native Component (TSX) using the tool provided at . While simple SVG icons have been successfully used be ...