Definition of method type within an object literal

I'm facing a situation where I have an async function nested inside an object. In order to maintain proper type declarations, I need to structure it like the example below:

interface Props {
  loading?: boolean | undefined;
  separator?: 'cell' | 'none';
  onRequest?: (requestProp: {
    pagination: {
      sortBy: string;
      descending: boolean;
      page: number;
      rowsPerPage: number;
    };
    filter: string;
  }) => void;
}

const myObj = {
  async myTest({ pagination }) {  // How do I set myTest as Props['onRequest']?
  let $id = this.id;
      /* consume $id and await */
      /* ... */
  },
  id: 521,
  result: '',
};

Is there a specific way to define the type of a method in an object literal?

Answer №1

Explore the following options:

Implement arrow functions

const object1 = {
    id: 235,
    myTest: async ({pagination}) => {
        console.log(`this = ${this}`);
        console.log(`object1.id = ${object1.id}`, )
    }
}

When using this approach, this is assigned to globalThis, resulting in undefined (refer to here).

[LOG]: "this = undefined" 
[LOG]: "object1.id = 235" 

Utilize regular functions

const object2 = {
    id: 813,
    myTest: async function({pagination}) {
        console.log(`this = ${JSON.stringify(this)}`);
        console.log(`object2.id = ${object2.id}`, )
        console.log(`this.id = ${this.id}`)
    }
}

This code snippet will yield:

[LOG]: "this = {"id":813}" 
[LOG]: "object2.id = 813" 
[LOG]: "this.id = 813" 

Comment 1 Updates

To begin, I separated the RequestProp type for better function signature usage. The subsequent steps remain consistent:

interface RequestProp {
  pagination: {
    sortBy: string;
    descending: boolean;
    page: number;
    rowsPerPage: number;
  };
  filter: string;
}

interface Props {
  loading?: boolean | undefined;
  separator?: "cell" | "none";
  onRequest?: (requestProp: RequestProp) => Promise<void>;
}

async function main() {
  const x: Props = {
    onRequest: async function (requestProp: RequestProp) {
      console.log(JSON.stringify(requestProp, null, 2));
    },
  };

  if (x.onRequest) {
    const json = await x.onRequest({
      pagination: {
        sortBy: "x",
        descending: true,
        page: 1,
        rowsPerPage: 10,
      },
      filter: "xyz",
    });

    console.log(json);
  }
}

main();

Answer №2

In my quest for a solution, I stumbled upon the power of utilizing Parameters and NonNullable utilities.

    const newObj = {
      async newTest( {pagination} : Parameters<NonNullable<QTableProps['onRequest']> ) {  
      let $id = this.id;
          // extracting pagination
          /* use $id and await */
          /* ... */
      },
      id: 521,
      outcome: '',
    };

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

Error: Angular 4.1.3 routing is unable to locate child module within parent module

Thanks in advance for any help! Greetings, I'm encountering the following error as described in the title. Despite my attempts at troubleshooting and research, I am unable to resolve it. Below are some important files - can anyone with experience in ...

Encountering a problem with TypeScript while employing Promise.allSettled

My current code snippet: const neuroResponses = await Promise.allSettled(neuroRequests); const ret = neuroResponses.filter(response => response?.value?.data?.result[0]?.generated_text?.length > 0).map(({ value }) => value.data.result[0]?.genera ...

Error in Ionic 3: "this is null"

Whenever I fetch data from Firebase, I am attempting to redirect accordingly. If the data is null or empty, then there is no need for redirection. My attempt involves using this.navCtrl.push(ProspectPage); but for some reason, it is not functioning proper ...

Dealing with API Errors in Ngrx

I came across an interesting scenario in the ngrx example-app provided on Github. When starting a new project, I always strive to follow the best practices, so I referred to the example app for guidance. In one particular instance within the application, t ...

Encountering issues with accessing the clientWidth and clientHeight references of the DOM in Vue

Issue with 'clientWidth' and 'clientHeight' properties on Vue and Element types. <div class="invoice-step-detail" id="invoice" ref="invoice"> @Component({ name: 'CreateInvoice', co ...

Modifying the property of an object following retrieval from the server

I find myself a bit perplexed about the optimal approach for modifying a value in an object once it has been retrieved from a server. Here is my TypeScript Script: import { Component, OnInit } from '@angular/core'; import { Response } from &apo ...

Error: The 'contains' property is not available for type 'never'

I'm facing a persistent error that is making my file display in red. I attempted to include types while using useRef(null), but the error continues to persist. Could it be possible that I am assigning incorrect types? const dropdownRef = useRef(null) ...

A promise was caught with the following error: "Error in ./Search class Search - inline template:4:0 caused by: Maximum call stack size exceeded"

As a newcomer to Angular2, I am currently developing a web application that requires three separate calls to a REST API. To test these calls, I decided to simulate the API responses by creating three JSON files with the necessary data. However, my implemen ...

Troubleshooting a deletion request in Angular Http that is returning undefined within the MEAN stack

I need to remove the refresh token from the server when the user logs out. auth.service.ts deleteToken(refreshToken:any){ return this.http.delete(`${environment.baseUrl}/logout`, refreshToken).toPromise() } header.component.ts refreshToken = localS ...

Is it possible to import in TypeScript using only the declaration statement?

Is there a way to use a node module in TypeScript without explicitly importing it after compilation? For example: I have a global variable declared in a file named intellisense.ts where I have: import * as fs from 'fs'; Then in another file, ...

(NextAuth) Error: The property 'session' is not found within the existing type '{}'

While working on a NextJs project with NextAuth, I encountered the following error: "Type error: Property 'session' does not exist on type '{}'.". To resolve this issue, I added the session property to my _app.tsx file as sugg ...

Update the TypeScript definitions in the index.d.ts file using the npm command, by overriding it with the reference types

After running npm install, I noticed that the index.d.ts file contains a reference to the wrong path: /// <reference types="[WrongPath]"/>. As someone new to npm, TypeScript, and web development in general, I'm wondering if it's possible t ...

Angular error message: Trying to access the property 'name' of an undefined object leads to a TypeError

I'm having trouble phrasing this question differently, but I am seeking assistance in comprehending how to address this issue. The error message I am encountering is as follows: TypeError: _co.create is not a function TypeError: Cannot read property ...

Discovering a locator based on the initial portion of its value

Here's a piece of code that is used to click on a specific locator: await page.locator('#react-select-4-option-0').click(); Is there a way to click on a locator based on only the initial part of the code, like this: await page.locator(&apos ...

Failing to reach the nested if statements within a switch case block

Before removing my question, please read this. Despite testing with console.logs, my code does not enter the if statements. I have not come across a similar solution to my issue. In an attempt to address any timing or asynchronous problems, I added a use ...

Can Angular be utilized for developing an email application?

Can an email application be developed using Angular? I attempted to incorporate a nodejs script, but encountered issues when using the nodejs script within an Angular TS file, resulting in the following error: Error: Module not found: Error: Can't re ...

Angular 4 fetches the number obtained from a GET request

In my spring-boot back-end app, I have defined a query as shown below: @Query("SELECT COUNT(*) " + "FROM Foo " + "WHERE name = :name and surname = :surname ") Integer countByNameAndSurname(@Param("name") String name, @Param("surnam ...

Fatal Error: Unable to resolve dependencies for ProductListComponent

I'm currently developing an Angular 6 app and encountering an error when trying to inject a service into my component. The error message Uncaught Error: Can't resolve all parameters for ProductListComponent: (?) is not providing specific details, ...

I am experiencing difficulties with implementing Angular material components in my project

I recently encountered an issue while trying to integrate angular material into my project. Despite importing the MatFormFieldModule, I received the following error: ERROR in src/app/login/components/login/login.component.html:2:1 - error NG8001: &apo ...

A peculiar quirk with Nuxt.js radio buttons: they appear clickable but are somehow not disabled

I’m having an issue with a radio button that won’t check. It seems to be working fine on other pages, but for some reason it just won't click here. <div class="form-group"> <label class="control-label&q ...