Specify specific data types for a dynamically generated class method

Imagine having a scenario with the following class:

class Example {
  method1 = this.generateDynamicFunction((param: string) => {
    return "string" + param;
  });

  method2 = this.generateDynamicFunction((param: number) => {
    return 1 + param;
  });

  generateDynamicFunction(fn: (param: any) => any) {
    return (param) => fn(param);
  }
}

const instance = new Example()
instance.method1('text') // => stringtext
instance.method2(5) // => 6

How can I define the types for the functions Example.prototype.method1 and Example.prototype.method2? I aim to explicitly specify that method1 accepts and returns a string, while method2 accepts and returns a number.

Admittedly, this example is somewhat contrived. In my current project, I am in the final stages of revamping one of my message queue client libraries where many class functions are created dynamically. These functions share common functionalities but have varying input and output types.

Answer №1

Generics provide a flexible solution:

class Foo {
  bar = this.createCustomFunction((param: string) => {
    return "string" + param;
  });

  baz = this.createCustomFunction((param: number) => {
    return 1 + param;
  });

  createCustomFunction<Type>(fn: (param: Type) => Type) {
    return (param : Type) => fn(param);
  }
}

const foo = new Foo()
//console.log(foo.baz(2)) // => 3
console.log(foo.bar('baz')) // => barbaz
console.log(foo.baz(2)) // => 3

You define a generic function, allowing for any type to be used. This gives you the flexibility to set the overall function type based on that type

Playground Link

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

Finding the total of values within an array in Angular 2 and Ionic 2 by utilizing *ngfor

As I work on developing a mobile application using Ionic 2, my current task involves calculating the total allocation sum (Course.allocation) for each year per horse in the database. For instance: Table: Course (Race): [Id_course: 1, allocation: 200, dat ...

How Typescript Omit/Pick erases Symbols in a unique way

Recently, I have delved into TypeScript and started working on developing some custom utilities for my personal projects. However, I encountered an issue with type mapping involving Pick/Omit/Exclude and other typing operations where fields with symbol key ...

After updating the state in a Reducer with Redux Toolkit, make sure to utilize a

Issue: Seeking efficient code writing methods. Here is a detailed example of my Redux Toolkit slice below: import { createSlice } from '@reduxjs/toolkit'; import { setCookie } from '../../utils/storageHandler'; const initialState = { ...

A helpful guide to adjusting the cursor placement within a contenteditable div using React

I am developing a custom text editor using a contenteditable div. Each time a user modifies the text inside it, I aim to enclose all the new text with a strong element and update the div's innerHTML accordingly. Here is what I have attempted (utilizi ...

Error message: Unable to locate module when utilizing my alternative library packaged with Rollup

Currently, I am utilizing rollup to package a UI library for use across various primary applications. However, the bundled ESM file contains imports that are incompatible with webpack in the main applications: import { ArrowDropDownCircleOutlined } from &a ...

Incorporate a personalized button within the actions column of ng2-smart-table for Angular 2 development

Within the context of an ng2-smart-table component in Angular 2, I am attempting to include a new button within the actions column that, when clicked, will navigate to another page. Despite my efforts to implement this new button alongside the existing add ...

Angular is known to raise the error ExpressionChangedAfterItHasBeenCheckedError

I am currently developing an Angular application using Angular version 7.0.4. My objective is to automatically set focus on the first input element of a modal if the list of working times contains more than one element. However, I am facing an issue where ...

Effortless code formatting with VS Code for TypeScript and JavaScript

Does anyone know of any extensions or JSON settings that can help me format my code like this: if(true) { } else { } Instead of like this: if(true){ } else { } ...

Utilizing Template Literals within Typescript

Currently, I am facing a challenge with retrieving a variable from an object. cell: (row: any) => `${row.testcolumn}` The issue arises because I do not know the value of 'testcolumn' in advance since this process is dynamic. Despite my attem ...

How to configure VSCode for automatically transpiling TypeScript and launching NodeJS debugger with just one press of the F5 key?

Working with VSCode+TypeScript+NodeJS can feel overly complex compared to a C# project in Visual Studio. Just hitting F5 in C# compiles the project and initiates debugging. How can I configure VSCode to do the same for TypeScript+NodeJS? What am I missing ...

The Kubernetes cluster unexpectedly closes down following a period of processing

My GCP cluster is hosting a NodeJS server. The server functions flawlessly when run locally, but mysteriously stops without any error messages when I attempt to send a post request to a specific route. This post request is supposed to trigger the sending o ...

MatTableDataSource failing to showcase remote dataSource in mat-table component

I am experiencing issues while trying to incorporate a component using mat-table with data source from a Remote Server. The table is not displaying the data as expected. html <div class="mat-elevation-z8"> <mat-form-field> <input ...

Nested Tagged Union Types in Typescript

Imagine having the following types (syntax similar to Elm/Haskell): type Reply = LoginReply | LogoutReply type LoginReply = LoginSucceeded | AlreadyLoggedIn String When trying to represent this in Typescript using discriminated unions, a challenge arises ...

How to efficiently register services for multiple instances in Angular

Currently, my service includes a field that represents a ViewContainerRef and a method to set the value of this field. @Injectable({ providedIn: 'root' }) export class SomeService { public viewContainerRef: ViewContainerRef setViewContaine ...

Storing Data Locally in Angular with User Authentication

Using angular8, I encountered an issue where logging in with USER1 credentials, closing the browser, and then attempting to log in with USER2 credentials still logged me in as USER1. While adding code to the app component resolved this problem, I faced an ...

What could be the reason for my Angular 2 app initializing twice?

Can someone help me figure out why my app is running the AppComponent code twice? I have a total of 5 files: main.ts: import { bootstrap } from '@angular/platform-browser-dynamic'; import { enableProdMode } from '@angular/core'; impor ...

If a component does not have a specified return type annotation, it will default to an 'any' return type

I'm struggling to understand the typescript error that keeps popping up, it says: 'MyGoogleLogin', which doesn't have a return-type annotation, is being given an implicit 'any' return type. All I want is for the component t ...

React Native TypeScript Issue: Exported member 'Appearance' not found in module "react-native"

I recently added dark mode to my app, but I'm running into an issue when building the npm package using npm build. The code functions correctly, but I'm wondering if there's a way to eliminate this error or if there's a reason for it to ...

Angular HttpClient Catch Return Value

In my quest to develop a universal service for retrieving settings from the server, I've encountered an issue. When errors arise, I want to intercept them and provide a default value (I have a predetermined configuration that should be utilized when e ...

Retrieve request body/header variables in JWT strategy using Nest JS

Is there a way to retrieve the header variables or request body in a strategy? The JWT structure within the JwtStrategy currently appears as follows: @Injectable() export class JwtStrategy extends PassportStrategy(Strategy) { constructor( private re ...