What is the process for invoking a Promise<Response>?

Using the fetch method, I make a request to an API to retrieve JSON data.

The custom function that I created returns a Promise<Response> (this is a simplified version).

const getData = (): Promise<Response> => fetch('http://the.api.com').then(response => response.json())

This is how I implement it:

export class Case {
  Uuid?:       string
  Topic?:      string
  public constructor(init?:Partial<Case>) {
    Object.assign(this, init);
  }
}

getData()
  .then(response => allCases.value = response.Data as Array<Case>) // the error occurs in this line
  .catch(() => {{}})

The issue I'm facing: TypeScript shows me an error message:

TS2339: Property 'Data' does not exist on type 'Response'.

The application still runs successfully, but I would like to resolve this error for better understanding of TypeScript in general.

I attempted to specify the type for response:

interface ApiResponse {
  Data: Array<Case>
}

getData('/case', 'GET')
  .then((response: ApiResponse) => allCases.value = response.Data as Array<Case>)
  .catch(() => {{}})

Now, two errors are displayed:

TS2345: Argument of type '(response: ApiResponse) =&gt; Case[]' is not assignable to parameter of type '(value: Response) =&gt; Case[] | PromiseLike&lt;Case[]&gt;'.
Types of parameters 'response' and 'value' are incompatible.
Property 'Data' is missing in type 'Response' but required in type 'ApiResponse'.

ESLint: This assertion is unnecessary since it does not change the type of the expression. (@typescript-eslint/no-unnecessary-type-assertion)

How can I indicate that the output from my custom function should be treated as an Object with a Data key?

Answer №1

To create the function callApi, you can use the following code:

const callApi = (): Promise<ApiResponse> => fetch('http://the.api.com').then(r => r.json())

After examining the type definitions of node-fetch, it becomes clear that:

  • The return type of fetch is Promise<Response>
  • The return type of Response.json is Promise<unknown>

Therefore, the correct return type of your callApi function is Promise<unknown>, not Promise<Response>.

A corrected version would look like this:

callApi().then(r => allCases.value = r.Data).catch(() => {{}})

Your previous approach failed due to:

callApi('/case', 'GET')
    .then((r: ApiResponse) => allCases.value = r.Data as Array<Case>)
    .catch(() => {{}})

In this scenario, you provided an incorrectly-typed callback function to then because the type of

r</code is not <code>ApiResponse</code as expected, but rather <code>Response
based on your initial typing. This inconsistency caused a TypeScript error.

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

I am unable to process the information and transform it into a straightforward list

When using ngrx, I am able to retrieve two distinct data sets from storage. private getCatalog() { this.catalogStore.select(CatalogStoreSelectors.selectAllCatalogsLoadSuccess) .pipe( takeWhile(() => this.alive), take(1), ...

Error: In Angular and Typescript, the function this.$resource is not recognized

I keep encountering a TypeError: this.$resource is not a function. Below is the code snippet causing the issue: export class DataAccessService implements IDataAccessService { static $inject = ["$resource"]; constructor(private $resource: ng ...

Obtaining the Current Component Instance in SolidJS

Is it possible to retrieve the Component that is currently active in SolidJS, along with its props, signals, internal state, effects, etc.? I'm searching for a solution similar to React's __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCu ...

Retrieving the event name from a CustomEvent instance

Looking to retrieve the name of a CustomEvent parameter in a function, which is basically the string it was created with (new CustomEvent('foo')) If you need a reference, check out https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent ...

Importing components with local data within an ngFor in Angular TypeScript

Having recently started working with Angular2, I am facing a challenge with importing components in ngFor loops. The issue seems to arise when importing components with data in ngFor loops; it checks for values in the .ts file instead of the local variabl ...

Guide to Implementing npm Package 'latlon-geohash' in Angular 7

I'm encountering an issue while attempting to utilize the latlon-geohash npm package within my Angular 7 application. When I execute it, I encounter the following error... ERROR TypeError: latlon_geohash__WEBPACK_IMPORTED_MODULE_8__.encode is not ...

Dot notation for Typescript aliases

Here are the imports I have in my TypeScript source file: import {Vector as sourceVector} from "ol/source"; import {Vector} from "ol/layer"; This is how Vector is exported in ol/source: export { default as Vector } from './source/ ...

Global variable's value cannot be accessed outside the function in which it was inserted

I am facing an issue where I cannot access the value of var Login inside submit() function. This could possibly be due to a race condition. What could be causing this blockage in accessing the value of var Login? Here is the code snippet: class ABC { ...

Can Typescript automatically determine the return type based on the function argument value?

How can Typescript be utilized to deduce the return type from the valueType parameter instead of using overloads? type ValueType = 'integer' | 'string' | 'number' | 'date' | 'dateTime' | 'boolean&apos ...

What is the best way to add a service to a view component?

I am facing an issue with my layout component where I am trying to inject a service, but it is coming up as undefined in my code snippet below: import {BaseLayout, LogEvent, Layout} from "ts-log-debug"; import {formatLogData} from "@tsed/common/node_modul ...

My variable from subscribe is inaccessible to Angular2's NgIf

My goal is to display a spinner on my application while the data is being loaded. To achieve this, I set a variable named IsBusy to True before making the service call, and once the call is complete, I set IsBusy to false. However, I am facing an issue wh ...

Guide on triggering a bootstrap popup modal using a TypeScript file

I am currently working on an Angular project where I need to launch a popup modal when my function is called. I came across an example on w3schools, but it only contains the HTML logic to open the popup. What I want to achieve is to open the popup from th ...

Information sent from TypeScript frontend to Java backend is converted into a LinkedHashMap

I have a situation where my typescript frontend is communicating with my java backend using REST. Recently, I added a new simple rest endpoint but encountered an issue when trying to cast the sent object properly because the body being sent is a LinkedHash ...

The type 'string' does not share any properties with the type 'CSSProperties'

How can I resolve the issue of Type 'string' has no properties in common with type 'CSSProperties'? const points = 100; const radius = 257; const max = 100; const peaks = [ 10, 50, 90 ]; const step = ...

Discovering the following solution in JavaScript

I am a beginner in the field of web development and seeking help in generating a specific output for a given problem: var totalRows = 5; var result = ''; for (var i = 1; i <= totalRows; i++) { for (var j = 1; j <= i; j++) { res ...

Issue with the onClick event in next.js and TypeScript

While working on the frontend development of an app, I encountered a strange issue with the onClick function. The error message I'm seeing is: Type '(e: SyntheticEvent<Element, Event>) => void' is not assignable to type 'Custom ...

Utilizing the polymer paper-dialog component in an Angular 2 TypeScript application

I have imported the paper-dialog from bower, but I am facing an issue with showing the dialog using the open() method. app.component.html <paper-icon-button icon="social:person-outline" data-dialog="dialog" id="sing_in_dialog" (click)="clickHandler()" ...

Conceal specific elements across various paths in Angular 5

Attempting to hide a component based on matching routes, it is currently working with one route but not with multiple routes. import { Component } from '@angular/core'; import { Router } from '@angular/router'; @Component({ select ...

Tips for calculating the total count of a specific field within a JSON array with TypeScript

I have a JSON array. "user": { "value": [ { "customerNo": "1234" }, { "customerNo": "abcd" }, { "c ...

The classification of rejected promises in Typescript

Is it possible to set the type of rejection for a promise? For example: const start = (): Promise<string> => { return new Promise((resolve, reject) => { if (someCondition) { resolve('correct!'); } else { ...