Executing Functions from Imported Modules in Typescript

Is there a way to dynamically call a method from my imported functions without hard-coding each function name in a switch statement? I'm looking for a solution like the following code:

import * as mathFn from './formula/math';

export function loadMethod(fnName: string, params: string){
   mathFn[fnName](params); 
}

I've attempted the following solution:

type SupportedMathFunction = keyof typeof mathFn;

export function loadMethod(fnName: SupportedMathFunction, params: string){
       mathFn[fnName](params); 
}

However, this approach is still giving errors.

Is there a way to retrieve methods from imported items using their names?

When compiling Typescript in VSCODE Terminal, I encountered the following Error:

SyntaxError: Unexpected token '?'
at wrapSafe (internal/modules/cjs/loader.js:1047:16)
at Module._compile (internal/modules/cjs/loader.js:1097:27)
at Module.m._compile (...\node_modules\ts-node\src\index.ts:1043:23)
at Module._extensions..js (internal/modules/cjs/loader.js:1153:10)
at Object.require.extensions.<computed> [as .ts] (...\node_modules\ts-node\src\index.ts:1046:12)
at Module.load (internal/modules/cjs/loader.js:977:32)
at Function.Module._load (internal/modules/cjs/loader.js:877:14)
at Module.require (internal/modules/cjs/loader.js:1019:19)
at require (internal/modules/cjs/helpers.js:77:18)
at Object.<anonymous> (...\src\functions.ts:11:1)

Update:

I resolved the error by upgrading Node from 12.16.3 to the latest version 14.15.5 and running npm update. Although, I faced Jasmine related issues, so I downgraded ts-node to version 8.10.2 based on this question Jasmine-ts throwing an error about package subpath, which ultimately allowed the code to work with my own solution:

type SupportedMathFunction = keyof typeof mathFn;
  
export function loadMethod(fnName: SupportedMathFunction, params: string){
   mathFn[fnName](params); 
}

Furthermore, @Lesiak's solution proved to be more convenient:

function loadMethod<K extends keyof typeof mathFn>(fnName: K ): typeof mathFn[K]{
  return mathFn[fnName]; 
}

Answer №1

Here is a solution to improve your code:

function getMathFunction<K extends keyof typeof mathFn>(funcName: K): typeof mathFn[K] {
       return mathFn[funcName];
}

This revised code addresses two key issues in your original implementation:

  • It includes the necessary function keyword.
  • Avoids undefined parameters.

Furthermore, this function now simply loads the specified math method without executing it immediately. It also ensures that each returned method has the correct type signature.

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

The not-null constraint is violated in the "id" column because of a null value when using Sequelize Typescript

My Database Setup Journey Recently, I embarked on a database adventure where I decided to use Sequelize-Typescript to assist me with all the heavy lifting in terms of database operations. The first step was creating a table called uma_tbl_users, and here ...

Compile time extraction of constant string from type field

I am currently facing an issue with a field in my type that contains a constant string literal. My goal is to be able to reference both the type and field by name so that I can utilize this string literal throughout my code. Here is an example: export type ...

Creating sparse fieldset URL query parameters using JavaScript

Is there a way to send type-related parameters in a sparse fieldset format? I need help constructing the URL below: const page = { limit: 0, offset:10, type: { name: 's', age:'n' } } I attempted to convert the above ...

What is the reason for encountering a TypeScript error when using a union type?

interface Bird { age:string, eat:()=>any } interface Fish { age:string, swim:()=>any } type Pet = Fish | Bird; everything looks good so far, defining a Pet type const pet:Pet={ age:"sd", eat:()=>{} } when trying to return ...

Creating a function that operates according to the input parameter

Imagine a scenario where I am working with the following JS function: function fetchValue(keyName) { return x => x[keyName]; } Is it possible to define fetchValue in such a way that Typescript's type inference automatically determines the outp ...

Can you please provide a step-by-step guide for using socket.io with TypeScript and webpack, after installing it

Currently, I am experimenting with TypeScript in conjunction with node.js, socket.io, and webpack. To facilitate this setup, I have configured the webpack.config.js, tsconfig.json, and tsd.json files. Additionally, I acquired the typings file for socket.i ...

Combine all TypeScript enums into a single one

Looking for a way to combine two separate enums into one for easier use. export enum ActionTypes1 { ClearError = 'CLEAR_ERROR', PrependError = 'PREPEND_ERROR', } export enum ActionTypes2 { IncrementCounter = 'INCREMENT_COUNT ...

Learn how to dynamically import external modules or plugins using the import() functionality of TypeScript 2.4 within the production script generated by Angular CLI

Utilizing the typescript 2.4 [import()][1] feature has proven to be effective for dynamically loading modules. Testing this functionality has shown positive results, especially when importing modules and components located within the same directory. Howev ...

What is the best way to retrieve Express app configuration asynchronously?

I am utilizing an Express app developed with the Serverless Framework, which will be hosted via AWS API Gateway and AWS Lambda. The authentication process is handled by Okta, and I am considering storing the necessary secrets in SSM. Currently, I have to f ...

What could be the reason for a property going unnoticed during the iteration of a list?

The Scenario There is a class named myClass: export class myClass { name: string; age: number; city: string; } and another class called people: export class people { name: string; age: number; } In the component.ts, a variable list ...

Expo + tRPC: Oops! Looks like the application context couldn't be retrieved. Don't forget to wrap your App inside the `withTRPC` HoC for

I'm currently working on a straightforward tRPC server setup: // server.ts import { initTRPC } from "@trpc/server"; import { z } from "zod"; const t = initTRPC.create(); export const appRouter = t.router({ greeting: t.procedu ...

Union does not contain the specified property in Typescript

Here are the types that I have: Foo { foobar: any } Bar { fooBarBar: any; } I want to use a function defined like this: this.api.submit(param: Foo | Bar) When trying to use it, I encountered an issue: this.api.submit(param.foobar) // does no ...

Enhancing collaboration: Seamlessly sharing interface/interface/model files in the integration of

Currently, I am engrossed in developing an application with an Express backend and Typescript whilst utilizing Angular for the frontend. The only snag I'm facing is that I require interface/models files from the backend to be accessible on the fronten ...

Adding custom CSS and JavaScript to an Angular 4 project can be done by including the necessary

When working with Angular 2, I was able to include stylesheets directly in the index.html like so: <link rel="stylesheet" href="css/mycss.css"> However, with Angular 4, the styles need to be added to the angular-cli.json file within the styles and ...

Angular: ngx-responsive has a tendency to hide elements even if they meet the specified conditions

Recently, I started using a library called this to implement various designs for desktop and mobile versions of an Angular app (v4.2.4). Although the documentation recommends ngx-responsive, I opted for ng2-responsive but encountered issues. Even after set ...

Having Trouble with Angular 6 Subject Subscription

I have created an HTTP interceptor in Angular that emits a 'string' when a request starts and ends: @Injectable({ providedIn: 'root' }) export class LoadingIndicatorService implements HttpInterceptor { private loadingIndicatorSour ...

Utilize PrimeNG's async pipe for lazy loading data efficiently

I have a significant amount of data (400,000 records) that I need to display in a PrimeNG data table. In order to prevent browser crashes, I am looking to implement lazy loading functionality for the table which allows the data to be loaded gradually. The ...

Transforming a material-ui component from a class to a function

Currently, I am in the process of learning material-ui, and it seems that most of the code examples I come across are based on classes. However, the new trend is moving towards using functions instead of classes due to the introduction of hooks. I have be ...

What is the best way to test the validity of a form while also verifying email availability?

I am currently working on implementing async validation in reactive forms. My goal is to disable the submit button whenever a new input is provided. However, I am facing an issue where if duplicate emails are entered, the form remains valid for a brief per ...

Can you explain the correct method for assigning types when destructuring the `callbackFn.currentValue` in conjunction with the `.reduce()` method? Thank you

I'm working with an array of arrays, for example: const input = [['A', 'X'], ['B', 'Y'],...]; In addition to that, I have two enums: enum MyMove { Rock = 'X', Paper = 'Y', Scis ...