TypeScript class methods share the same overloaded signature as the constructor function

I am currently in the process of adding TypeScript typings to a third-party JavaScript library. The majority of the class methods require another instance of the same class as input and return a new instance. However, they also accept overloaded constructor arguments in place of an actual instance. I am looking for a way to avoid repeating the same overloaded signature for each method within the class in my .d.ts file.

For instance, I could manually list out each method like so...

class Foo {
  constructor(x: number);
  constructor(x: number, y: number);
  constructor({ x: number, y: number });

  Fizz(foo: Foo): Foo;
  Fizz(x: number): Foo;
  Fizz(x: number, y: number): Foo;
  Fizz({ x: number, y: number }): Foo;

  Buzz(foo: Foo): Foo;
  Buzz(x: number): Foo;
  Buzz(x: number, y: number): Foo;
  Buzz({ x: number, y: number }): Foo;

  // Repeat for other methods
}

However, it would be more efficient to achieve something like this...

class Foo {
  constructor(x: number);
  constructor(x: number, y: number);
  constructor({ x: number, y: number });

  // Ideally, I would like a syntax similar to...
  Fizz(constructor()): Foo;
  Buzz(constructor()): Foo;
}

Is there a simple way to declare and reuse an overloaded method signature?

Answer №1

If you want to streamline the signatures for member functions, it can be done quite easily:

// Simplifying the signatures
type CreatesFoo = {
    (foo: Foo): Foo;    
    (x: number): Foo;
    (x: number, y: number): Foo;
    (obj: { x: number, y: number }): Foo;
}

class Foo {
  constructor(x: number);
  constructor(x: number, y: number);
  constructor(obj: { x: number, y: number });
  constructor(...args:any[]) {}


  Fizz: CreatesFoo = (): any => {
  }

  Buzz: CreatesFoo= (): any => {
  }

  // and so on for various methods
}

Keep in mind that the constructor cannot be merged into the same signature. The easiest approach is to simply list it out individually as shown above 🌹

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

How to extract values of variables from a typescript file with gulp

I have a bunch of typescript files, and some of them export a constant called APIS. I'm attempting to access these exports (with the goal of combining them into one file), but for some reason it's not working. I know I must be making a mistake s ...

Get notified with ng2-smart-table updates when editing

I am trying to control the edit feature of my ng2-smart-table, but the code I have isn't working. Am I missing something? HTML <ng2-smart-table [settings]="settings" [source]="source" (edit)="onEdit($event)"></ng2-smart-table> Component ...

Learn how to import from a .storybook.ts file in Vue with TypeScript and Storybook, including how to manage Webpack configurations

I'm currently utilizing Vue with TypeScript in Storybook. Unfortunately, there are no official TypeScript configurations available for using Vue with Storybook. How can I set up Webpack so that I am able to import from another .storybook.ts file with ...

Ensuring TypeScript enforces the validation of deconstructed props

Why isn't Typescript checking props when I use destructuring? I've already experimented with the strict flag in Typescript Let's discuss a simple component const Component = (props: { foo: string }) => <div />; The following cod ...

Using Angular material to display a list of items inside a <mat-cell> element for searching

Can I use *ngFor inside a <mat-cell> in Angular? I want to add a new column in my Material table and keep it hidden, using it only for filtering purposes... My current table setup looks like this: <ng-container matColumnDef="email"> < ...

Utilizing Object.fromEntries in Typescript

I am attempting to define a type called ObjectFromEntries that functions similarly to the return type of the Object.fromEntries function. Here is what I have so far: type ObjectFromEntries<Entries extends [keyof any, any][]> = { [key in Entries[numb ...

Choosing multiple values in Angular Material Select - automatically preselected items

Taking on the role of an Angular developer, my task involves receiving a JSON-entity from an API and assigning its values to a FormGroup. Despite everything working as expected (with all values present in the FormGroup), the issue lies with the visual pres ...

Exploring solutions to this problem with the use of classes, vectors, and other related methods

Recently, I began learning OOP C++ from scratch, despite having prior programming experience. The current focus is on classes, objects, and constructors. While I grasped the concept to some extent, I encountered a specific task that is proving challenging. ...

Toggle the visibility of a dropdown menu based on the checkbox being checked or unchecked

One challenge I am facing involves displaying and hiding DropDown/Select fields based on the state of a Checkbox. When the checkbox is checked, the Dropdown should be visible, and when unchecked, it should hide. Below is the code snippet for this component ...

Trying out a react component with the useSelector hook for testing

I've been struggling to write tests for a component that uses the useSelector hook from react redux. Despite looking at similar questions and suggested solutions, I still can't seem to resolve my issue. The troublesome part of my component, name ...

Parameters in Typescript decorators

Can someone help me understand the various parameters of a Typescript decorator? function myDecorator(target) { // do something with 'target' ... } In the given example, I am aware that 'target' represents the function/class to wh ...

Utilizing a JSDoc comment from an external interface attribute

Currently, I am in the process of developing a React application. It is common to want the props of a child component to be directly connected to the state of a parent component. To achieve this, I have detailed the following instructions in the interface ...

Typescript: Defining a universal interface for a React component or HTML element along with its corresponding properties

I am in the process of creating a unique wrapper interface. In my search, I have come across some intriguing types: Imagine Bar as a React component that requires props of type BarProps. Consider Z as the interface that serves as a representation for any ...

Tips on preventing image previews from consuming too much text data while updating a database in Angular 12 using Material UI for image uploads within a FormGroup object

Currently working with Angular 12 and Angular Material for image uploads with preview. I have a formgroup object below, but I'm running into issues with the 197kb image preview text being inserted into the database. Despite trying setValue/patchValue/ ...

Encountering an issue accessing a property retrieved from a fetch request in TypeScript

I am currently dealing with the property success defined in the API (reCAPTCHA). /** * The structure of response from the veirfy API is * { * "success": true|false, * "challenge_ts": timestamp, // timestamp of the challen ...

Can one generate an enum based on a specific type?

I have a preference: preference Preference = 'OptionA' | 'OptionB' Is it feasible to generate an enumeration from this preference? For instance: enumeration Enum = { OptionA, OptionB } I am uncertain about the feasibility of this. ...

Exploring the nuances of checking lists in TypeScript

In the following list: empList = ['one','two','finish','one','three'] I am required to evaluate conditions based on empList: Condition 1: If 'two' appears before 'finish', set this ...

What is the validity of using Promise.reject().catch(() => 5) in Typescript?

Can you explain why the TS compiler is not flagging an error for this specific code snippet? Promise.reject().catch(() => 5) Upon inspecting the definition of the handler function within the catch, we come across the following code: interface Promise&l ...

Guide to importing items from a personalized library with extensive exporting

After updating my library structure by adding some directories, I am facing an issue with importing types from it. Below is the updated structure of the library : |-dist (built typescript) |-src |--business |---entities |----user.ts |----site.ts |---useca ...

Tabulator: Adding a new row with merged columns in Tabulator

Is there a method to insert a new row in Tabulator that spans multiple columns? view image here I am looking for something similar to this, where data is displayed across more than one column. I need to incorporate additional details retrieved from an aj ...