Indicate the type of method without transforming it into a property

If I have a method in my application that delegates its functionality to an external library method, and I know the type for that external method (e.g. LibDoStuffMethodType), how can I specify the type for my method MyApp.doStuff() without making it a property?

class MyApp {
  doStuff(args) {
     // delegate to external library's lib.doStuff
  }
}

I could make doStuff() a property of MyApp:

class MyApp {
  doStuff: LibDoStuffMethodType
}

However, this is not ideal for reasons such as poor IntelliSense support. So, is there any way to keep the method as a method while also specifying its full type as LibDoStuffMethodType?

Answer №1

There is a suggestion already posted on microsoft/TypeScript#22063 proposing to allow function statements and method definitions to be typed using a function/callable type alias or interface. Currently, there doesn't seem to be much progress on this, but if you feel strongly about it, consider showing your support by giving it a thumbs up or leaving a comment.


If that feature is not available, an alternative could be creating an interface that must be implemented by your class:

type LibDoStuffMethodType = (x: string, y: number) => boolean
interface DoStuffMethod { doStuff: LibDoStuffMethodType };

class MyApp implements DoStuffMethod {
  doStuff(a: string, b: number) {
    return true;
    // delegate to external library's lib.doStuff
  }
}
declare const myApp: MyApp;
myApp.doStuff; // now functions as a method

The class MyApp now includes a legitimate method named doStuff, but it is restricted to the type LibDoStuffMethodType!


While this approach works to a certain extent, it may be frustrating that you have to explicitly define the method's parameters and return type. It would be ideal if these could be inferred from the DoStuffMethod interface automatically, but unfortunately, this is not currently possible (see microsoft/TypeScript#1373). Therefore, any straightforward solution will likely involve some repetition.

Is there a way around this? If LibDoStuffMethodType is a specific single function type without overloads or generics, you can utilize the Parameters<T> and ReturnType<T> utility types for programmatically annotating the parameter list and return type:

class MyApp implements DoStuffMethod {
  doStuff(...args: Parameters<LibDoStuffMethodType>): ReturnType<LibDpStuffMethodType> {
    return true;
    // delegate to external library's lib.doStuff
  }
}

This does help with keeping the code DRY, but there are several caveats to consider, making it potentially unsuitable for your needs. Other workarounds may exist, but they might encounter similar limitations.

This represents the closest approximation I could achieve.

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

When utilizing DomSanitizer, Angular2 suddenly ceases to function properly

I've been working with Angular 2 and TypeScript. Everything was going well until I encountered an issue with my pipe, which is causing the DomSanitizer to interfere with the (click) event functionality. Even though the (click) code appears intact in ...

What potential drawbacks come with utilizing the OOP approach in both JavaScript and React?

While working on an internal project, I found myself creating a base system and implementing a custom form structure using TypeScript with an OOP approach. class Form extends React.Component {} abstract class FormElement extends React.Component<{valid ...

Creating a table with merged (colspan or rowspan) cells in HTML

Looking for assistance in creating an HTML table with a specific structure. Any help is appreciated! Thank you! https://i.stack.imgur.com/GVfhs.png Edit : [[Added the headers to table]].We need to develop this table within an Angular 9 application using T ...

How to identify the type of a union type in Typescript

I am curious about the type c used in the printTypeOf function. Check out my code below: type Email ={ email:string, } type Phone ={ phone:string, } type ContactInfo = Email | Phone; function printTypeOf(c: ContactInfo) { console.log(typeof c ...

Is it possible for transclusion to display content from external sources using *ngIf and <ng-content>?

In my Angular4 Project, I have come across this snippet of code: <div class="divider"></div> <ng-content select=".nav-toggle"></ng-content> Now, I am trying to figure out a way to display the divider only when there is content pr ...

Encountering the ExpressionChangedAfterItHasBeenCheckedError error during Karma testing

Testing out some functionality in one of my components has led me to face an issue. I have set up an observable that is connected to the paramMap of the ActivatedRoute to retrieve a guid from the URL. This data is then processed using switchMap and assigne ...

Creation of source map for Ionic 2 TypeScript not successful

Struggling with debugging my Ionic 2 application and in need of guidance on how to include souceMap for each typescript file that corresponds to the javascript files. Despite enabling "sourceMap":true in my tsconfig.json file, the dev tools in Chrome do n ...

the "then" function is causing issues in my TypeScript Node code

My code looks like this: var fs = require('fs'); var util = require('util'); var files = fs.readdirSync('*/path to my folder that contains subfolders*/') async function getfilenum(){ var files_v_num = [] for(const i in fi ...

Angular 4 with Typescript allows for the quick and easy deletion of multiple selected rows

I am currently working on an application where I need to create a function that will delete the selected checkboxes from an array. I have managed to log the number of checkboxes that are selected, but I am struggling to retrieve the index numbers of these ...

Having trouble reaching a public method within an object passed to the @Input field of an Angular component

My configurator object declaration is as follows. export class Config { constructor(public index: number, public junk: string[] = []) { } public count() : number { return this.junk.length; } } After declaring it, I pass it into the input decorated fi ...

How can I assign a true or false value to an input variable in HTML using AngularTS?

I copied the following HTML code: <tag-input fullWidth id="inputDir" formControlName="inputDir" [modelAsStrings]="true" [placeholder]="'choice feature'" ...

The isAuthenticated status of the consumer remains unchanged even after being modified by a function within the AuthContext

I am working on updating the signout button in my navigation bar based on the user's authentication status. I am utilizing React Context to manage the isAuthenticated value. The AuthProvider component is wrapped in both layout.tsx and page.tsx (root f ...

How to set the type of an object property to a string based on a string from an array of strings in TypeScript

Great { choices: ['Bob', 'Chris', 'Alice'], selectedChoice: 'Alice', } Not So Good { choices: ['Bob', 'Chris', 'Alice'], selectedChoice: 'Sam', } I've been exp ...

TimeStamp Recorder - Typescript

I'm trying to create a timer that counts the time when a button is pressed. Currently, I have managed to display the minutes and seconds on the screen as soon as the button is clicked. For example: 21(min):02(sec) What I am struggling with is updati ...

angular 2 updating material table

Issue at Hand: I am facing a problem with the interaction between a dropdown menu and a table on my website. Imagine the dropdown menu contains a list of cities, and below it is a table displaying information about those cities. I want to ensure that whe ...

Upgrading the import package alias from 'angular2' to '@angular'

Is there a way to update the package alias for import purposes? I am trying to utilize ng2-bootstrap, which requires @angular/core, but I have been referencing it as angular2/core. This mismatch is causing my screen to crash! ...

Emotion, material-ui, and typescript may lead to excessively deep type instantiation that could potentially be infinite

I encountered an issue when styling a component imported from the Material-UI library using the styled API (@emotion/styled). Error:(19, 5) TS2589: Type instantiation is excessively deep and possibly infinite. Despite attempting to downgrade to typescript ...

Guide to loading TypeScript modules with RequireJS in an ASP.NET MVC/Visual Studio setup

If we consider a scenario where there are 2 files named test1.ts and test2.ts. The content of test1 is as follows: export const x = 1 And the content of test2 is: import { x } from './test2' alert(x); Upon running the application, an error m ...

Accessing an unregistered member's length property in JavaScript array

I stumbled upon this unique code snippet that effectively maintains both forward and reverse references within an array: var arr = []; arr[arr['A'] = 0] = 'A'; arr[arr['B'] = 1] = 'B'; // When running on a node int ...

Can we condense the code to create a more concise and efficient function?

Can someone help me refactor this code snippet below into a function and combine the two IF statements? Many thanks! let value = productDetails.recentPurchaseDate; if (!productDetails.salesPrice && !productDetails.recentPurchaseDate) { value = false; } ...