Develop a wrapper for a function with multiple variations in TypeScript

Encountering an issue with the code below while attempting to create a proxy for a function with multiple overloads:

// The target function
function original (a: number): boolean;
function original (a: string): boolean;
function original (a: boolean): boolean;

function original (a: number | string | boolean): boolean {
  return true;
}

// The proxy
function pass (a: string | number){
  return original(a); // here
};

pass(5);
pass('a');
pass(true);

When trying to create a proxy for the original function, TypeScript throws the following error :

No overload matches this call.
  Overload 1 of 3, '(a: number): boolean', gave the following error.
    Argument of type 'string | number' is not assignable to parameter of type 'number'.
      Type 'string' is not assignable to type 'number'.
  Overload 2 of 3, '(a: string): boolean', gave the following error.
    Argument of type 'string | number' is not assignable to parameter of type 'string'.
      Type 'number' is not assignable to type 'string'.
  Overload 3 of 3, '(a: boolean): boolean', gave the following error.
    Argument of type 'string | number' is not assignable to parameter of type 'boolean'.
      Type 'string' is not assignable to type 'boolean'.(2769)
input.tsx(5, 10): The call would have succeeded against this implementation, but implementation signatures of overloads are not externally visible.

Key points to consider about this situation :

  • I've simplified the scenario to isolate when the problem occurs
  • The pass(true) call results in an error, indicating that typing seems to work for the pass function
  • In my specific case, the original function comes from a module, so any solution without modifying it would be ideal

View a TS Playground with the aforementioned code.

Answer №1

If your goal is to eliminate the error, one approach is to verify the type before executing the initial function call.

function checkTypeAndCallOriginal (input: string | number){
  if (typeof input === "number") {
    return originalFunction(input);
  } else if(typeof input === "string"){
    return originalFunction(input);
  }
  throw new Error(`Expected either a string or a number`);
};

Answer №2

Simply convert it to the required data type

function transform(a: number): boolean;
function transform(a: string): boolean;
function transform(a: boolean): boolean;

function transform(a: number | string | boolean): boolean {
  return true;
}

const result = transform as (a: string | number) => boolean

result(5);
result('a');
result(true);

Click here for more information

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

Tips on configuring a segment in an Angular 6 route

Question: I am looking to configure a specific segment after the user logs in, for example http://localhost:4200/#/{dynamic name}/{dynamic name}/app/... However, I am facing an issue when navigating to /app/... across the application. Is there a way to a ...

Restrict the scope of 'unknown' to an object containing only a string-field without resorting to 'any'

Currently, I am working on validating the data that is being received by my application. To illustrate, consider the following scenario: function extractField(data: unknown): string { if (typeof data !== 'object') { throw new Error(& ...

Deactivate the chosen tab by clicking the Mat-Tab button

I was trying to implement a way to disable the selected mat-tab and its elements when a button is clicked, //HTML <mat-tab-group #tabGroup> <mat-tab *ngFor="let subject of subjects" [label]="subject.name"> {{ subject.name }} ...

Is it possible to combine various SVG icons into a single component?

I am currently able to code SVGs in React-Native using typescript. This allows me to call them as individual react native components. Below is an example of my current capability: <View> <BackArrow color ="red" wid ...

Identifying when an element is in or out of view using Next.js and TypeScript

I'm currently working on an app using Next and Typescript. The app features a navigation bar at the top of the screen, and I need it to change its style once it reaches a certain point in the view. I attempted to use jQuery for this purpose, but encou ...

Transform JSON reply in JavaScript/Typescript/Angular

Looking for assistance with restructuring JSON data received from a server API for easier processing. You can find the input JSON file at assets/input-json.json within the stackblitz project: https://stackblitz.com/edit/angular-ivy-87qser?file=src/assets/ ...

Encountering error "An import path cannot end with a '.ts' extension." when importing TypeScript file in Vue Single File Component (SFC) within VS Code

Currently, I am in the process of transitioning my .vue components from using JavaScript to TypeScript. As a result, my single file components are structured as follows: <template> ...something... </template> <script lang="ts"> import ...

I'm unable to modify the text within my child component - what's the reason behind this limitation?

I created a Single File Component to display something, here is the code <template> <el-link type="primary" @click="test()" >{{this.contentShow}}</el-link> </template> <script lang="ts"> imp ...

Generate a commitment from the function

I know the basics of JavaScript Promise and promise chain, but I'm looking to deepen my understanding. For example, take a look at the method provided below. It's in TypeScript, but can be adjusted for JavaScript ES6. private InsertPersonInDB(p ...

Implementing TypeScript in an Asp.net Core ReactJS application`s configuration

After using Visual Studio 2022 to create an asp.net core Reactjs project, I discovered that everything was written in javascript instead of typescript. Is there a way to switch this project over to typescript? ...

Navigating back to the previous page with data in Angular 4 after switching from Angular 2

One scenario to consider is when page C features a Go Back button. On Page A, navigate to Page C with data and click the Go Back button to return to Page A with data. Similarly, on Page B, go to Page C with data and press the Go Back button to go back to ...

Using TypeScript's Non-Null Assertion Operators in combination with square brackets []

One way to assert that an object has a certain property is by using the `!.` syntax as shown below: type Person = { name: string; age: number; gender?: string; } const myPerson: Person = { name: 'John Cena', age: 123, gender: 's ...

Setting up a Lerna monorepo with TypeScript: A Comprehensive Guide

I have a central repository with the following details in config.json: "main": "dist/cjs/index.js", "module": "dist/esm/index.js", "es2015": "dist/es2015/index.js", "types": "dist/es2015/index.d.ts", "typings": "dist/es2015/index.d.ts", The repository co ...

What is the best way to trigger a function in React when a constant value is updated?

In my React application, I have 3 components. The parent component and two child components named EziSchedule and EziTransaction. Each component fetches its own data from an API. The data to display in the EziTransaction child component depends on the reco ...

Having trouble with Angular Ng2-file-Upload's Upload.all() method not successfully sending files to the API

Dealing with the challenge of uploading files in mp4 and jpg formats, I have set up 2 separate instances of FileUploader with custom validation. Upon clicking the upload button, I attempt to merge the files from both instances into a single FileUploader ...

What is the best way to retrieve the current complete URL in a Next.js/Typescript component?

I'm working on a component and I need to retrieve the current full URL. Here's a simplified version of what I have: /** * Share dropdown component */ export const ShareDropdown: React.FC<{ className: string }> = ({ className, }) => { ...

The onChange event will not be triggered in an input component that is not intended to be uncontrolled

Could someone please assist me in understanding why the onChange event is not being triggered? I am customizing ChakraUI's Input component to retrieve a value from localStorage if it exists. The component successfully retrieves the value from localS ...

Using the Moment library in a NestJS application

I am integrating momentjs into my nestjs application and I want to ensure that my services can be tested effectively. To achieve this, I have included momentjs in my module setup as shown below: providers: [ { provide: 'MomentWrapper', ...

The file located at 'node_modules/minimatch/dist/cjs/index' does not contain an exported element called 'IMinimatch'. Perhaps you intended to reference 'Minimatch' instead?

I encountered an error while using rimraf as a devDependency (v5.0.0) in my project. The error message I received was: node_modules/@types/glob/index.d.ts:29:42 - error TS2694: Namespace '".../node_modules/minimatch/dist/cjs/index"' has ...

This object does not have support for the attribute or method "getAttribute"

I've searched for solutions, but nothing seems to work for me and now I'm feeling quite lost. My current setup involves Cordova, Ionic, and Angular 2. Below is the HTML snippet: <ion-col *ngFor="let value of myButtonsFirstRow" width-25> ...