What is the best way to exceed the capacity of a function in TypeScript by incorporating optional

I've been working on converting some code from JavaScript to TypeScript, and I have a specific requirement for the return type of a function.

The function should return void if a callback parameter is provided, otherwise it should return Promise<object>. There's also an optional parameter called settings that can be passed before the callback parameter. In certain cases, the callback parameter could be passed in as the settings parameter, which the function handles with the initial few lines of logic.

To maintain backwards compatibility and avoid redundancy in code, I want to avoid creating separate functions like savePromise or saveCallback. So, I'm looking for a way to make TypeScript understand this logic intelligently.

type CallbackType<T, E> = (response: T | null, error?: E) => void;

class User {
    save(data: string, settings?: object, callback?: CallbackType<object, string>): Promise<object> | void {
        if (typeof settings === "function") {
            callback = settings;
            settings = undefined;
        }

        if (callback) {
            setTimeout(() => {
                callback({"id": 1, "settings": settings});
            }, 1000);
        } else {
            return new Promise((resolve) => {
                setTimeout(() => {
                    resolve({"id": 1, "settings": settings});
                }, 1000);
            });
        }
    }
}

const a = new User().save("Hello World"); // Expected type: Promise<object>, eventually resolves to {"id": 1, "settings": undefined}
const b = new User().save("Hello World", (obj) => {
    console.log(obj); // {"id": 1, "settings": undefined}
}); // Expected type: void
const c = new User().save("Hello World", {"log": true}); // Expected type: Promise<object>, eventually resolves to {"id": 1, "settings": {"log": true}}
const d = new User().save("Hello World", {"log": true}, (obj) => {
    console.log(obj); // {"id": 1, "settings": {"log": true}}
}); // Expected type: void

In my ideal scenario, the types for the function should look something like this:

save(data: string, settings?: object): Promise<object>;
save(data: string, callback: CallbackType<object, string>): void;
save(data: string, settings: object, callback: CallbackType<object, string>): void;

I've attempted to handle the case where the callback parameter is passed in as the settings parameter by defining the function signature as follows:

save(data: string, settings?: object | CallbackType<object, string>, callback?: CallbackType<object, string>): Promise<object> | void

However, this approach feels messy and it seems that TypeScript doesn't infer that settings will always be an optional object after the initial code block in the function. This leads to the need for explicit type casting when calling callback, which isn't ideal.

My question is, how can I achieve this behavior in TypeScript more elegantly?

Answer №1

TL;DR

In brief, the solution provided includes some refactoring:

type CallbackType<T, E> = (response: T | null, error?: E) => void;
interface ISettings {
  log?: boolean;
}
interface ISaveResult {
  id: number;
  settings: ISettings | undefined;
}

class User {
  save(data: string): Promise<ISaveResult>;
  save(data: string, settings: ISettings): Promise<ISaveResult>;
  save(data: string, callback: CallbackType<ISaveResult, string>): void;
  save(data: string, settings: ISettings, callback: CallbackType<ISaveResult, string>): void;
  save(data: string, settings?: ISettings | CallbackType<ISaveResult, string>, callback?: CallbackType<ISaveResult, string>): Promise<ISaveResult> | void {
    if (typeof settings !== "object" && typeof settings !== "undefined") {
      callback = settings;
      settings = undefined;
    }

    const localSettings = settings; // required for closure compatibility
    if (callback) {
      const localCallback = callback; // required for closure compatibility
      setTimeout(() => {
        localCallback({ id: 1, "settings": localSettings });
      }, 1000);
    } else {
      return new Promise((resolve) => {
        setTimeout(() => {
          resolve({ id: 1, "settings": localSettings });
        }, 1000);
      });
    }
  }
}

const a = new User().save("Hello World"); // User.save(data: string): Promise<ISaveResult>

const b = new User().save("Hello World", obj => { 
  console.log(obj); // obj: ISaveResult | null
}); // User.save(data: string, callback: CallbackType<ISaveResult, string>): void

const c = new User().save("Hello World", { "log": true }); // User.save(data: string, settings: ISettings): Promise<ISaveResult>

const d = new User().save("Hello World", { "log": true }, (obj) => {
  console.log(obj); // obj: ISaveResult | null
}); // User.save(data: string, settings: ISettings, callback: CallbackType<ISaveResult, string>): void

For a practical example, check out this illustration.

  • When inspecting settings within the if statement:

    https://i.sstatic.net/lWT3n.png

  • Upon evaluating settings inside the if block:

    https://i.sstatic.net/WfAsr.png

  • Error encountered during callback assignment:

    Type 'Function' is not assignable to type 'CallbackType'. Type 'Function' provides no match for the signature '(response: object | null, error?: string | undefined): void'.(2322)

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

TypeScript maintains the reference and preserves the equality of two objects

Retrieve the last element of an array, make changes to the object that received the value, but inadvertently modify the original last position as well, resulting in both objects being identical. const lunchVisit = plannedVisits[plannedVisits.length ...

Tips for displaying a multi-select dropdown in the Creative Tim Angular Material Pro filter panel

I am in need of assistance with modifying the standard Creative Tim Angular Pro Material template due to my limited CSS/SCSS skills. Could someone provide examples of the necessary changes, whether it involves altering the HTML or multiple CSS files withi ...

What is the most efficient way to convert a JSON object into a URL search parameter using as few characters as possible?

Challenge: On my web app, users can adjust settings to create or edit generative artworks and then share their creations via a shortened link. The objective is to store all the data needed to replicate the artwork in the URL within 280 characters. Initia ...

Unable to retrieve a method from the model class in Angular 4

I attempted to utilize a method from the model class, but encountered an error: ERROR TypeError: act.sayHi is not a function Below is my code snippet: Model Class myModelClass.ts export interface IMymodel { name: string; addres ...

When utilizing Ionic Firebase, the user profile saved in the sidemenu is stored using the Events class. However, the saved profile disappears as soon as

Hello there. I am currently working on displaying my user's information in the sidemenu, and after some research, I found that using the Events class might solve this issue. However, I have noticed that the data saved in subscribe gets destroyed whene ...

Is there a way for me to modify a value in Mongoose?

I have been attempting to locate clients by their ID and update their name, but so far I haven't been successful. Despite trying numerous solutions from various sources online. Specifically, when using the findOneAndUpdate() function, I am able to id ...

Problem encountered while initializing a new project using Angular-CLI version 6.1.2

After attempting to create a new Angular project using ng new angular-6-boilerplate, I encountered an issue with the latest version of angular-cli. Despite using the terminal for Windows to set up my project, an error occurred: The input for the schemat ...

Enhance the background property in createMuiTheme of Material-UI by incorporating additional properties using Typescript

I've been attempting to include a new property within createMuiTheme, but Typescript is not allowing me to do so. I followed the instructions provided here: https://next.material-ui.com/guides/typescript/#customization-of-theme I created a .ts file ...

What steps can I take to improve this code and prevent the error "Property 'patient' does not exist on type 'Request<ParamsDictionary>'" from occurring?

I'm having some issues with my code. I am attempting to use passport authenticate in order to save patient information that is specific to the token generated for each individual. router.get("/current", passport.authenticate("jwt", { session: false }) ...

Creating a searchable and filterable singleSelect column in the MUI DataGrid: A step-by-step guide

After three days of working on this, I feel like I'm going in circles. My current task involves fetching data from two API sources (json files) using the useEffect hook and storing them in an array. This array contains a large number of products and a ...

How come the props aren't being passed from the parent to the child component? (React / TypeScript)

Learning TypeScript for the first time and facing an issue with passing props from parent to child components. The error seems to be related to the type of props, but I'm not sure how to fix it since all types seem correct. Error message: "Property ...

The default value for an input of type date should be set to the current date

I am working on a project that involves an input field with the type of "date". I have implemented Materialize to provide a user-friendly date picker. My goal is to set the default value of this input field to the current date when it is initialized. Here ...

Expanding the base class and incorporating a new interface

(Here is an example written using Typescript, but it applies to other cases as well) class IMyInterface { doC:(any) => any; } class Common { commonProperty:any; doA() { } doB() { } } class ClassA extends Common {} class Clas ...

A TypeScript/Cypress command that restricts input parameters to specific, predefined values

I have a Cypress command with a parameter that I want to restrict so it only accepts certain values. For example, I want the columnValue to be limited to 'xxx', 'yyy', or 'zzz'. How can I achieve this? Cypress.Commands.add( ...

Issue: The variable 'HelloWorld' has been declared but not utilized

Why am I encountering an error when using TypeScript, Composition API, and Pug templating together in Vue 3? How do I resolve this issue when importing a component with the Composition API and using it in a Pug template? ...

What is the best way to determine the highest value?

How can I ensure that the data is displayed based on the condition c.date <= this.selectedReport.report_date? The current code snippet if (Math.max(...this.costs.map(c => c.date))){} seems to be causing an issue where no data is being displayed. What ...

Ways to dynamically link a JSON response object to an entity?

In my ng2 implementation, I have a user.service.ts file that calls a REST service and returns JSON data. The code snippet below shows how the getUser function retrieves the user information: getUser(id: number): Promise<User> { return this.http. ...

Combining functions does not result in a callable function, even when the parameters fulfill the constraints of each individual function

I have encountered an issue while trying to compile a Typescript snippet: function foo(v: string) { return 'foo'; } function bar(v: string | number) { return 'bar'; } const notCallable: typeof foo | typeof bar = function() {} as any; ...

Exploring the depths of a TypeScript interface with unknown levels of complexity

My current challenge involves a recursive function that operates on an object with a generic interface. This function essentially traverses the object and creates a new one with a nearly identical interface, except for the leaf nodes which are transformed ...

Capture individual frames from angular video footage

Trying to extract frames from a video using Angular has been quite challenging for me. While browsing through Stack Overflow, I came across this helpful post here. I attempted to implement the first solution suggested in the post, but unfortunately, I was ...