Is there a method to categorize class methods' parameters in a universally applicable manner?

Consider the code snippet below.

class MyClass {
  method1(arg1: string, arg2: number, arg3: number) {}
    
  method2(arg1: string, arg2: number, arg3: number) {}
}

I want to abstract out the argument types

arg1: string, arg2: number, arg3: number
for reuse.
Although not functional, the example below illustrates my intention.

interface MyClassMethodArgs {
  arg1: string;
  arg2: number; 
  arg3: number;
}

interface MyClass {
  // How can I represent "arg1: string, arg2: number, arg3: number" as MyClassMethodArgs?
  method1(arg1: string, arg2: number, arg3: number): void;
  method2(arg1: string, arg2: number, arg3: number): void;
}

class MyClassImpl implements MyClass {
  // How can I avoid repeating the type definitions of MyClass here?
  method1(arg1, arg2, arg3) {}
    
  method2(arg1, arg2, arg3) {}
}

Answer №1

One possible approach is as follows:

type ThreeNumFunction = (a: number, b: number, c: number) => void

class NewClass {
  func1: ThreeNumFunction = (a, b, c) => {
    // ...
  };
  func2: ThreeNumFunction = (a, b, c) => {
    // ...
  };
}

It's worth noting that this method creates new functions for each instance of the class rather than referencing existing ones within the class itself. This can impact performance and memory usage. In most cases, unless complex method signatures are required or explicit binding to instances is needed, the slight duplication may not be a major concern.

Furthermore, it's important to understand that achieving similar results with an interface is not feasible due to the inability to infer parameter types from method signatures within the interface:

interface NewInterface {
  func1: ThreeNumFunction;
  func2: ThreeNumFunction;
}

// Parameters are implicitly of type 'any'
class AnotherClass implements NewInterface {
  func1(a, b, c) {
    // ...
  }
  func2(a, b, c) {
    // ...
  }
}

Interactive Code Sample

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

Sending information from a parent component to a child component within an Angular application

How can I efficiently pass the this.formattedBookingPrice and this.formattedCheckingPrice values to a child component using the value array instead of static values, especially when they are inside the subscribe method? This is my parent component. expor ...

Event listener for iframe video player click in Angular 2+

I have a video iframe that starts playing automatically when the page loads: <section> <div class="row" > <div style="padding-top: 56.25%"> <iframe src="https://players.brightcove.net...& ...

Creating a TypeScript generic type for the "pick" function to define the types of values in the resulting object

I am facing an issue while writing the type for the pick function. Everything works smoothly when picking only one key or multiple keys with values of the same type. However, if I attempt to pick a few keys and their values are of different types, I encoun ...

The rule result is invalid due to the occurrence of the Function()

As I proceed with the upgrade from angular 6 to angular 7, I am diligently following the guidelines provided on the official Angular website. Upon executing the command to update angular/cli and core for version 7: $ ng update @angular/cli@v7 @angular/c ...

Customizable parameters in a React component

I am encountering two issues with the code provided below: interface MyForm { age: number; email: string; name: string; } function Form< T, ComponentProps extends { name: string; onChange: (event: React.ChangeEvent) => void; } &g ...

Receiving feedback from an http.post request and transferring it to the component.ts file in an Angular

Currently, I am facing an issue with passing the response from an http.post call in my TypeScript service component to an Angular 2 component for display on the frontend. Below are the code structures of my service.ts and component.ts: getSearchProfileRes ...

Guide on Linking a Variable to $scope in Angular 2

Struggling to find up-to-date Angular 2 syntax is a challenge. So, how can we properly connect variables (whether simple or objects) in Angular now that the concept of controller $scope has evolved? import {Component} from '@angular/core' @Comp ...

The declaration file (d.ts) is unable to access the type declaration

I am facing an issue with the following directory structure: dts/ my-types.d.ts lib/ a.ts a.d.ts b.ts b.d.ts Both a.ts and b.ts reference a common type called IFoo. To avoid redundancy, I decided to declare IFoo in a shared file located at dts ...

Changes were made to React Context, however, the components are not reflecting these updates

I've been experimenting with implementing the Context API using hooks in our company project. We're working with TypeScript. I've set up a Context, a Provider, and a Reducer. However, when I interact with buttons, the state changes but the c ...

What is the best way to create a type that excludes the character 'a' from a string?

Here is how I am attempting to define a specific type: type Response = { type: 'a', value: string } | { type: ???, // any other string except 'a' value: number } Do you think this can be done? I experimented with the foll ...

Creating an object with mapped properties from enumeration values using Typescript

I am trying to find a way to automatically create an object with values computed during compilation using enumeration values and pre-defined function calls. The basic concept is to associate certain arguments of a function with keys. For example, consider ...

Tips for managing local storage asynchronously

I have two files in my TypeScript application, namely: File 1 and File 2, In File 1, I want to save a value in local storage like this: private load() { return this.entityService .load(this.$scope.projectRevisionUid) ...

Encountering an issue while trying to npm install, can someone offer some assistance?

npm code E404 npm 404 Error - GET https://registry.npmjs.org/tsnode - Resource not discovered ...

The 'required' validator in Mongoose seems to be malfunctioning

I've been attempting to validate the request body against a Mongoose model that has 'required' validators, but I haven't been successful in achieving the desired outcome so far. My setup involves using Next.js API routes connected to Mo ...

Retrieving a Promise's value for an HTML Element

Hello, I'm new to working with React and JavaScript and could use some assistance. I have a function that returns a Promise that includes an interface. My goal is to access a variable in the interface and use it within <dl><dt>{//string va ...

Arranging data in a table by date with "."

My current use case involves working with a table that contains dates and empty strings. Despite expecting the sorting to behave a certain way, I've encountered an issue. Normally, when sorting with strings, the empty string would typically be placed ...

modification of class into hooks, receiving error message 'then' property is not found in type '(dispatch: any) => Promise<void>'

As a newcomer to React hooks, I have been converting code from class components to hooks. However, I am encountering an error message when trying to use 'then' in hooks that says 'Property 'then' does not exist on type '(dispa ...

Developing a constructor method that is conscious of data types

In my current scenario, I am dealing with a set of types: X, Y, and Z, all of which extend the same common interface J. My goal is to define a method that looks like this: class MyClass { private someNumber = 1; private someProperty; addEleme ...

Filtering Typescript by property values of an interface that match its own values

Looking to extract specific types based on a given label Take a look at the code snippets below: interface TypeWithLabel { label: string; list: string; } interface A extends TypeWithLabel{ label: 'a'; list: '1' | &apo ...

Having trouble importing an object from another file in Typescript?

I'm facing a peculiar issue where I am unable to import a const declared in one file into another file. When trying to import the const, a TS error pops up stating Module '"../resources/dummy_container"' has no exported member &apo ...