"Utilize a callback function that includes the choice of an additional second

Concern

I am seeking a basic function that can receive a callback with either 1 or 2 arguments.

  1. If a callback with only 1 argument is provided, the function should automatically generate the second argument internally.
  2. If a callback with 2 arguments is supplied, the function should not call the second argument. It needs to be invoked within the callback instead.

Playground


Issue

TS2769: No overload matches this call.

Overload 1 of 2, '(callback: Callback): void', gave the following error.   
Argument of type '(a: any, b: any) => void' is not assignable to parameter of type 'Callback'. 

Overload 2 of 2, '(callback: Callback): void', gave the following error.
Argument of type '(a: any, b: any) => void' is not assignable to parameter of type 'Callback'.

Code

type B = () => void;

interface Callback {
  (a: number): void;
  (a: number, b: B): void;
  (a: number, b?: B): void;
}

function test(callback: Callback): void;
function test(callback: Callback): void;
function test(callback: Callback): void {
  const a = 1;
  const b = () => console.log('hello');

  if (callback.length === 1) {
    callback(a);

    b(); // calling "b" directly
  }

  if (callback.length === 2) {
    callback(a, b);
  }
}

//    |--| ERROR
test((a, b) => {
  console.log(a);

  b();
});

Answer №1

Having an abundance of overloads is unnecessary

type B = () => void;

interface Callback {
  (a: number, b?: B): void;
}

function test(callback: Callback): void {
    const a = 1;
    const b = () => console.log('hello');

    switch (callback.length) {
        case 1: callback(a); b(); break;
        case 2: callback(a, b); break;
    }
}

test((a, b) => {
  console.log(a);
  
  if (typeof b === "function") {
    b()
  }
});

test((a) => { console.log(a); });

Check out the example on the TS Playground

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

Issue with Jest: receiving error message "Module cannot be found" despite having the package installed

Recently, I went through a cleanup and update process for a private package to make it compatible with Vite. Initially, the package.json file had the following structure: { "name": "@myRegistry/my-package", "version": &qu ...

What is the best way to define a function agreement in Typescript?

I have created a function that can return `undefined` only when its argument is also `undefined`, otherwise it will always return a value derived from the argument provided. Here's an example of how the function works: function triple(value?: number) ...

Keep the list up-to-date by adding new items promptly

Utilizing Angular 7, I have implemented the following service (Click here for StackBlitz Example): @Injectable({ providedIn: 'root' }) export class TodoService { todos: BehaviorSubject<Todo[]> = new BehaviorSubject([ { id: 1, tit ...

RxJs will only consider the initial occurrence of a specific type of value and ignore any subsequent occurrences until a different type of value is encountered

I'm faced with a situation where I need to extract the first occurrence of a specific value type, followed by the next unique value of a different type. Let's break it down with an example: of(1,1,1,1,2,3,4) .pipe( // some operators ) .subsc ...

A more efficient method for refreshing Discord Message Embeds using a MessageComponentInteraction collector to streamline updates

Currently, I am working on developing a horse race command for my discord bot using TypeScript. The code is functioning properly; however, there is an issue with updating an embed that displays the race and the participants. To ensure the update works co ...

Creating a custom data type using values from a plain object: A step-by-step guide

I recently came across an object that looks like this: const myObject = { 0: 'FIRST', 10: 'SECOND', 20: 'THIRD', } My goal is to define a type using the values from this object, similar to this: type AwesomeType = &apos ...

Dynamically importing TypeScript interfaces for React code splitting

Is it possible to utilize dynamic import('path') for an exported interface? ...

Triggering an event from a higher-level component to a lower-level component

Within the parent component named personDetails, there is a Submit button. This parent component contains multiple child components called person`. Each time I click on the Submit button, I need to trigger a method within the child component. Is it possib ...

displaying post data in the URL address bar

During the development of my portal using angular 5, everything was running smoothly in the testing environment. However, due to production requirements, I made some changes to access modifiers from private to public. This modification has caused issues in ...

What are the steps for transforming my 2D array to fit a specific schema using RxJS?

UPDATE I stumbled upon a potential solution that I have appended to my question and am now seeking a more refined approach. In the context of an Angular 9 application, I am working with a two-dimensional array that I need to restructure. Through my use of ...

Bringing in TypeScript from external Node packages

I am looking to organize my application by splitting it into separate node modules, with a main module responsible for building all other modules. Additionally, I plan to use TypeScript with ES6 modules. Below is the project structure I have in mind: ma ...

Tips for importing a non-namespaced module TypeScript definition into my custom types

When working with my custom types, I want to utilize the GraphQLSchema from the graphql module. If I simply write: interface MyThing { schema: GraphQLSchema } It doesn't reference the actual GraphQLSchema definition from the module (it's just ...

Property element does not exist in this basic TypeScript project

I'm diving into my initial TypeScript project and encountering an issue with the "style". I attempted to utilize style!, create an if(changeBackgroundColor){}, but without success. let changeBackgroundColor = document.querySelectorAll('[data-styl ...

Exploring Angular2 Heroes Guide - Declaring Hero Properties with Nested Objects

Currently, I am diving into the Angular2 Tour of Heroes guide and striving to grasp the concept of services. So far, I've successfully implemented the basic tutorial, but as I attempt to add more complexity, my application crashes without clear reason ...

Error: Unable to access the property of an undefined variable in Angular 4

Here is what I currently have in my code: <p *ngIf="model.something.satisfy"> Yes </p> <p *ngIf="!model.something.satisfy"> {{model.something.comments}} </p> The issue arises in the second line with the error message "Type ...

Retrieve the values of private variables within a defined function

While experimenting with typescript, I have encountered an issue that I can't seem to resolve. My project involves using Angular, so I will present my problem within that context. Here is a snippet of my code: class PersonCtrl{ private $scope: I ...

Error encountered with the Angular 2 routing system

Currently, I am facing an issue with my Angular 2 router module. Whenever I try to access the link /city, I encounter an error message saying 'ERROR Error: Uncaught (in promise): Error: Cannot activate an already activated outlet Error: Cannot activat ...

"What is the significance of the .default property in scss modules when used with typescript

When dealing with scss modules in a TypeScript environment, my modules are saved within a property named default. Button-styles.scss .button { background-color: black; } index.tsx import * as React from 'react'; import * as styles from ' ...

Retrieving information selectively using useSWRImmutable

Having issues fetching data using useSWRImmutable. The problem arises when attempting to display the fetched data inside the UserRow component. Even though I can successfully print the data outside of the UserRow component, any console.log() statements wi ...

The variable 'data' is not a property of the type 'any[]'

I am currently facing an issue with a dummy service I created to fetch dummy data. When calling this service from a component ts file, I encountered the following error. After searching through some similar posts, I still haven't been able to resolve ...