What is the process for generating a function instance based on this TypeScript interface?

I'm having difficulty understanding the syntax of this interface. It seems to be overloaded, and I am getting an error from the compiler when trying to create a function with one signature but missing the other. My objective here is to mock this function for a Jest unit test.

interface SearchResultSetEachFunction {
  promise(callback: (result: Result) => boolean): Promise<boolean>;
  (callback: (result: Result) => boolean): void;
}

Answer №1

It's not overloaded; instead, it is a function that also includes a property called promise. You can create such an object using Object.assign:


let fn: SearchResultSetEachFunction = Object.assign(function (callback: (result: Result) => boolean): void {

}, {
    promise(callback: (result: Result) => boolean): Promise<boolean> {
      return Promise.resolve(false)
    }
})

Playground Link

In newer versions of TypeScript, you can use a function declaration and directly assign the promise member in the same scope as the declaration for TypeScript to recognize it as a new member:


function mockSearchResultSetEachFunction(callback: (result: Result) => boolean): void {

}
mockSearchResultSetEachFunction.promise = function (callback: (result: Result) => boolean): Promise<boolean> {
  return Promise.resolve(false)
}

let fn: SearchResultSetEachFunction = mockSearchResultSetEachFunction

Playground Link

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

The async and await functions do not necessarily wait for one another

I am working with Typescript and have the following code: import sql = require("mssql"); const config: sql.config = {.... } const connect = async() => { return new Promise((resolve, reject) => { new sql.ConnectionPool(config).connect((e ...

The limit of update depth when using useState with an array generated from a map operation

I'm working on a component where I'm creating a list from an array using map. Each li element in the list has a ref attached to it to capture the getBoundingClientRect().x and getBoundingClientRect().y coordinates, which are then stored in a refs ...

Searching for data based on specific keywords in Angular 2, rather than using a wildcard search, can be done by utilizing the key-in

My dropdown contains 100 values, and I am currently able to search for these values based on key input using wild search. However, I would like the dropdown to display values based on the specific alphabet that I enter first. HTML: <div class="col- ...

Error: Uncaught Angular8 template parsing issue

I used a tutorial from this website to guide me through my project. However, upon running my angular application, I encountered the following error in the console: Uncaught Error: Template parse errors: Can't bind to 'ngModel' since it isn ...

What is the significance of the KnownKeys type within IndexedDB?

type FilteredKeys<T> = { [K in keyof T]: string extends K ? never : number extends K ? never : K; } extends { [_ in keyof T]: infer U } ? U : never; This type is quite puzzling to me. I find it difficult to grasp its purpose. It appears to fil ...

Customize Typing for Properties in Subclasses of Lit-Element Using TypeScript

When extending a lit-element Class to add more specific typing, should the @property decorator be overridden or just the type and initializer? For example, consider the following code: interface AB { a: number, b: string, } @customElement('my- ...

Refreshing Form in Angular 2

When I remove a form control from my form, it causes the form to always be invalid. However, if I delete a character from another input field and then add the same character back in (to trigger a change event), the form becomes valid as expected. Is ther ...

Prevent scrolling using mousewheel click (auxclick event)

Currently working with Angular 9 and encountering an issue with the (auxClick) event triggering on a mousewheel click. The problem arises when attempting to use this event while there is a scroll present on the page, as it does not trigger correctly due to ...

Angular: Disabling a button based on an empty datepicker selection

Can anyone help me figure out how to disable a button when the datepicker value is empty? I've tried using ngIf to check if the datepicker is empty and then disable the button, but it's not working. My goal is to make the button unclickable if th ...

The UI elements are failing to reflect the changes in the data

In an attempt to establish communication between three components on a webpage using a data service, I have a Create/Edit component for adding events, a "next events" component for accepting/declining events, and a Calendar component for displaying upcomin ...

Leveraging Async / Awaits with Promise

Within my code, I have a specific promise chain that follows this structure: myPromise() .then(getStuffFromDb) .then(manipulateResultSet) .then(manipulateWithAsync) .then(returnStuffToCaller) An issue arises when working within the mani ...

Changing Angular templates and styles dynamically based on different conditions

I have a header component structured as follows: app-header (folder) classic (folder) app-header.component.html app-header.component.scss elegant (folder) app-header.component.html app-header.component.scss ...

Exploring Vue 3.3: Understanding Generics and Dynamic Properties

I'm currently diving into the generics feature in vue 3.3 and I've been pondering about defining the type of an incoming prop based on another prop value. This is my current component structure: export interface OptionProps { id: string | numb ...

TypeScript: restrict access to field to exclusive classes only

Here's an interesting dilemma I am facing. In my project, I adhere to the MVVM architecture pattern where I have separate Views for display logic and ViewModels for functional logic. The ViewModels contain methods and fields that can be accessed by ot ...

Tips on updating TypeScript to a higher major version

Despite upgrading all packages, deleting node_modules and package-lock.json, and reinstalling with npm install, the typescript runtime in my git repo is still showing version 4.9.5. How can I update the tsc version to be higher than 5.0? $ npx tsc --versi ...

Utilizing Tick formatting in Chart.js with Typescript: A step-by-step guide

When setting Chart.js to use the en-US locale, the scale numbers are formatted optimally. https://i.sstatic.net/fzjpQmM6.png If I try using a tick callback as shown in the documentation: ticks: { callback: function(value) { return value.toStr ...

Name values not appearing in dropdown list

Looking for some assistance with displaying a list of names in a dropdown menu using Angular. The dropdown is present, but the names from my array are not appearing. I think it might be a simple fix that I'm overlooking. I'm new to Angular, so an ...

Execute function every 5 seconds based on the current state

I have a method in my component that retrieves data from the back end and checks statuses. Here it is: getRecognitionById() { this.loaderService.show(null, true); this.vendorWebApiService .createRecognition(this.executiveChangeId) .pi ...

Is there a more efficient way to write the code below using MergeMap or FlatMap or other rxJs operators?

I have a situation where I have two observable pipes and I need to run them one after the other in order to compare their emitted values. The code snippet I attempted is provided below. Ideally, when the first observable emits a value, it should then fet ...

Incorporate an Array of Objects into the UseState hook with an initial value

I have encountered an issue with the following error message: "Error: Objects are not valid as a React child (found: object with keys {fzfvhv76576, user }). If you meant to render a collection of children, use an array instead." I have been attem ...