The request/response is missing property "x" in type "y" but it is required in type "z" during fetch operation

I have configured an interface specifically for utilization with an asynchronous function:

interface PostScriptTagResponse {
  script_tag : {
    readonly id : number
    , src : string
    , event : string
    , readonly created_at : string
    , readonly updated_at : string
    , display_scope? : string
  }
}

protected async createScriptTag(): Promise<PostScriptTagResponse|null> {
    try {
      const data: PostScriptTagResponse = await fetch(fetchUrl, {
        method: 'post'
        , headers: {
          "X-Shopify-Access-Token": this.generalToken
          , "Content-Type": "application/json"
        }
        , body: {
          script_tag : {
            src: `${this.serverHost}/server/frontEndScriptControl.js`
            , event: "onload"
            , display_scope: "online_store"
          }
        }
      }).json();

      return data.script_tag;
      // Property "script_tag" is missing in type {detailed interface spec here} 
      // but required in type "PostScriptTagResponse"
    }
    catch (e) {
      // removed
    }    
  }

Upon revisiting the aforementioned code snippet, I believe the structure to be accurate. Could there be a flaw in my understanding? Below is an example of the response I anticipate from the fetch request:

https://help.shopify.com/en/api/reference/online-store/scripttag#create-2019-10
HTTP/1.1 201 Created
{
  "script_tag": {
    "id": 870402694,
    "src": "https://djavaskripped.org/fancy.js",
    "event": "onload",
    "created_at": "2019-10-16T16:14:18-04:00",
    "updated_at": "2019-10-16T16:14:18-04:00",
    "display_scope": "all"
  }
}

Answer №1

The issue lies within these 3 lines:

protected async createScriptTag(): Promise<PostScriptTagResponse|null> {
      const data: PostScriptTagResponse = await fetch(fetchUrl, {
      return data.script_tag;

You are waiting for data, which is of type PostScriptTagResponse. Then you are returning a property (script_tag) of it, which is most likely not of type PostScriptTagResponse. However, your function signature expects you to return a PostScriptTagResponse.

To fix this, you can either modify the function signature like this:

protected async createScriptTag(): Promise<YourScriptTagType|null> {

Or you can return the response as it is and access the .script_tag property outside the function.

 protected async createScriptTag(): Promise<PostScriptTagResponse|null> {
      return await fetch(fetchUrl, { //...

Since your function is named createScriptTag, it's likely that you should go with the first approach.

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

When a ListView item is clicked, a label will display text with text wrapping specific to the selected item in the list

Within the listview items, there is a label that should expand when clicked. For example, initially it only shows one line of text. Upon clicking on the label, it should expand to show 10 lines of text. Current Issue: At present, when I click on the firs ...

What is the proper way to compare enum values using the greater than operator?

Here is an example enum: enum Status { inactive = -1, active = 0, pending = 1, processing = 2, completed = 3, } I am trying to compare values using the greater than operator in a condition. However, the current comparison always results in false ...

I'm having trouble installing node-sass and encountering an error. Can anyone offer advice on how to resolve this issue?

Encountering an error while trying to install node-sass, can someone assist me in resolving this issue? npm ERR! code EPERM npm ERR! syscall rename npm ERR! path C:\Users\deepe\OneDrive\Documents\Yajnaseni\POC\language&bs ...

Defining the range of an array of numbers in TypeScript: A complete guide

When working with Next.js, I created a function component where I utilized the useState hook to declare a variable for storing an array of digits. Here is an example: const [digits, setDigits] = useState<number[]>(); I desire to define the range of ...

The error message "Type 'IPromise<{}>' is not compatible with type 'IPromise<TemplatesPagingModel>' in typescript version 2.8.0" is displayed

Currently, I am working on an AngularJS framework (version 1.5.8) with the latest TypeScript files (version 2.8.0). However, after updating to the most recent TypeScript version, the code below is not compiling. Implementation of Angular interface: inter ...

The 'disabled' property is not found in the 'MatButton' type, however, it is necessary in the 'CanDisable' type

Issue found in node_modules/@angular/material/core/option/optgroup.d.ts: Line 17: Class '_MatOptgroupBase' does not correctly implement interface 'CanDisable'. The property 'disabled' is missing in type '_MatOptgroupBas ...

What is the best way to loop through an object while keeping track of its value types

I have a JSON file containing UI adjustments sourced from the API: interface UIAdjustmentsJSON { logoSize: number; themeColor: string; isFullScreen: boolean; } To simplify things, let's utilize a static object: const adjustments: UIAdjust ...

The React Typescript error message: "Type '' is not compatible with type 'null'"

I have started working on a simple todo app using React and TypeScript. As I am creating a context, I encountered an error regarding the value of the content provider. <TodoContext.Provider value={contextValue}>{children}</TodoContext.Provider> ...

Using LitElement: What is the best way to call functions when the Template is defined as a const?

When the template is defined in a separate file, it's not possible to call a function in the component. However, if the template is defined directly as returning rendered HTML with this.func, it works. How can one call a function when the template is ...

Webpack and React.js: Additional loaders might be required to manage the output generated by these loaders

An error occurred while parsing the module in ./productFlow/index.tsx at line 3, column 12. The file was processed with the following loaders: * ./node_modules/awesome-typescript-loader/dist/entry.js. It seems like an additional loader may be needed to h ...

Angular Component Test Results in TypeError Error Failure

After defining a custom error class called CustomError: export class CustomError extends Error { constructor(message?: string) { super(message); Object.setPrototypeOf(this, CustomError.prototype); } } I want to throw instances of ...

"Encountering a problem with the debounceTime operator in rxjs and HTTP requests while using the keyup

I have been working on implementing server-side search in Angular 7. I managed to find some code for implementation, but unfortunately it is not functioning as expected. The issue I am encountering is that when searching for a string, the code sends mult ...

Is a donut chart graph visible on the webpage?

After successfully creating a bar chart, I decided to work on a donut chart using Angular and d3.js. However, despite creating the donut chart, I'm facing an issue with displaying it on the screen. The DOM shows that it is present, but for some reason ...

Explain to me the process of passing functions in TypeScript

class Testing { number = 0; t3: T3; constructor() { this.t3 = new T3(this.output); } output() { console.log(this.number); } } class T3 { constructor(private output: any) { } printOutput() { ...

Draggable bar charts in Highcharts allow users to interact with the data by clicking

I'm working on creating a chart that allows for setting values by clicking and dragging. While the dragging functionality is working fine, I've run into an issue with the click event. When I click to set a new value, the draggable feature acts er ...

Angular JS and TypeScript - Issue: ng:areq Invalid Argument "Argument 'XXXXXX' is not a function, received undefined"

Encountering a specific error mentioned in the title. I organized models and controllers into distinct files saved under models and controllers folders respectively. Upon trying to establish a connection between them, I received an error stating "ng:areq ...

How to link observables in HTTP requests using Angular 5?

I'm currently developing an application using Angular 5, and I want to segregate raw http calls into their own services so that other services can modify the responses as needed. This involves having a component, component service, and component data ...

Create a new function and assign it to "this" using the button inside ngFor loop

I am working with a li tag that has a *ngFor directive: <li *ngFor="let items of buttons"> <button (click)="newMap(items.id, $event)"> {{ items.name }} </button> </li> The buttons array looks like this: buttons = [ {nam ...

Utilizing material-ui with Autocomplete featuring various value and option types

In my code, I am looking to store only an option's ID in a value For autocomplete functionality, the value's type and the option's type need to be the same My solution was to change the value in onChange, which worked successfully However ...

I require the ability to identify and capture the ID of the button (touchable opacity) that has been

When trying to delete a selected button by obtaining its specific id, I am facing an issue where after the first execution, the id of the deleted item is retained instead of the newly selected one. I am in need of a solution that allows me to retrieve the ...