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

Using Angular 5 to access a variable within a component while iterating through a loop

I am currently in the process of transferring code from an AngularJS component to an Angular 5 component. Within my code, I have stored an array of objects in a variable called productlist. In my previous controller, I initialized another empty array nam ...

Problem: Unable to locate the TypeScript declaration file

I am facing an issue with my TypeScript configuration. I have two files in /src/models/: User.ts and User.d.ts. In User.ts, I am building a class and trying to use an interface declaration for an object defined in User.d.ts. However, User.ts is unable to a ...

Is it possible to overlook TypeScript errors when compiling with Angular 2 AoT?

My application is experiencing numerous TypeScript errors, even though it runs correctly. I recently migrated a JavaScript app to TypeScript and am struggling to resolve all the type-related issues. In order to proceed with development, I have configured m ...

Is it possible to switch the hamburger menu button to an X icon upon clicking in Vue 3 with the help of PrimeVue?

When the Menubar component is used, the hamburger menu automatically appears when resizing the browser window. However, I want to change the icon from pi-bars to pi-times when that button is clicked. Is there a way to achieve this? I am uncertain of how t ...

Apply a CSS class once a TypeScript function evaluates to true

Is it possible to automatically apply a specific CSS class to my Div based on the return value of a function? <div class="{{doubleClick === true ? 'cell-select' : 'cell-deselect'}}"></div> The doubleClick function will ret ...

In TypeScript, there is a mismatch between the function return type

I am new to TypeScript and trying to follow its recommendations, but I am having trouble understanding this particular issue. https://i.stack.imgur.com/fYQmQ.png After reading the definition of type EffectCallback, which is a function returning void, I t ...

multiple event listeners combined into a single function

I'm looking to streamline my button handling in JavaScript by creating just one function that can handle all the buttons on my page. Each button will trigger a different action, so I need a way to differentiate between them. I thought of using one eve ...

Different ways to reference a variable in Typescript without relying on the keyword "this" throughout the codebase

Can we eliminate the need to write "this" repeatedly, and find a way to write heroes, myHero, lastone without using "this"? Similar to how it is done in common JavaScript. https://i.stack.imgur.com/TZ4sM.png ...

Different tsconfigs assigned to various directories

In my project, I am using Next.js with TypeScript and Cypress for E2E tests. The challenge I am facing is configuring tsc to handle multiple configs for different folders. The tsconfig.json file in the project root for Next.js looks like this: { "c ...

Unable to export data from a TypeScript module in Visual Studio 2015 combined with Node.js

Within one file, I have the code snippet export class Foo{}. In another file: import {Foo} from "./module.ts"; var foo: Foo = new Foo(); However, when attempting to run this, I encountered the following error: (function (exports, require, module, __file ...

Ensuring type safety at runtime in TypeScript

While delving into the concept of type safety in Typescript, I encountered an interesting scenario involving the following function: function test(x: number){ console.log(typeof x); } When calling this method as test('1'), a compile time er ...

Exploring Several Images and Videos in Angular

I'm experiencing a challenge with displaying multiple images and videos in my Angular application. To differentiate between the two types of files, I use the "format" variable. Check out Stackblitz export class AppComponent { urls; format; on ...

react-i18next: issues with translating strings

I encountered a frustrating issue with the react-i18next library. Despite my efforts, I was unable to successfully translate the strings in my application. The relevant code looked like this: App.tsx: import i18n from 'i18next'; import { initR ...

Is your TypeScript spread functionality not functioning as expected?

I'm new to TypeScript, so please forgive me if I've made an error. On a guide about TypeScript that I found online, it states that the following TypeScript code is valid: function foo(x, y, z) { } var args = [0, 1, 2]; foo(...args); However, w ...

How can data be transferred between controllers in Angular 2 without using URL parameters or the $state.go() function?

I've encountered an issue where I need to pass a parameter from one controller to another without it being visible in the URL. I attempted to do so with the following code: this.router.navigate(['/collections/'+this.name], {id: this.id}); ...

The Angular custom modal service is malfunctioning as the component is not getting the necessary updates

As I develop a service in Angular to display components inside a modal, I have encountered an issue. After injecting the component content into the modal and adding it to the page's HTML, the functionality within the component seems to be affected. F ...

Transitioning a codebase from @angular-builders/custom-webpack to NX for project optimization

I need help migrating my Angular project from using "@angular-builders/custom-webpack" build targets to transitioning to an integrated NX monorepo. When I run the command npx nx@latest init --integrated, I receive the following warning: Unsupported build ...

Issue with Nestjs validate function in conjunction with JWT authentication

I am currently implementing jwt in nest by following this guide Everything seems to be working fine, except for the validate function in jwt.strategy.ts This is the code from my jwt.strategy.ts file: import { Injectable, UnauthorizedException } from &ap ...

A TypeScript utility type that conditionally assigns props based on the values of other properties within the type

There is a common need to define a type object where a property key is only accepted under certain conditions. For instance, consider the scenario where a type Button object needs the following properties: type Button = { size: 'small' | &apo ...

Error in typescript: The property 'exact' is not found in the type 'IntrinsicAttributes & RouteProps'

While trying to set up private routing in Typescript, I encountered the following error. Can anyone provide assistance? Type '{ exact: true; render: (routerProps: RouterProps) => Element; }' is not compatible with type 'IntrinsicAttribu ...