Executing a series of imported functions from a TypeScript module

I'm developing a program that requires importing multiple functions from a separate file and executing them all to add their return values to an expected output or data transformation. It's part of a larger project where I need these functions to seamlessly integrate without modifying the core library code.

For instance:

export function func1() : any {
    return {test1: "test1"}
}

export function func2() : any {
    return {test2: "test2"}
}

export function func3() : any {
    return {test3: "test3"}
}

Relevant Functions in Separate File

import * as val_funcs from "path/to/val_func/file"

function get_val_list() : any {
// Need to iterate through each function in val_funcs
// Executing each one, collecting the value, then returning it 
}

I'm uncertain about how to achieve this task or what specific keywords to search for answers. Despite trying different search queries like "how to run each function in a list in TypeScript", I haven't found a useful solution yet.

Answer №1

If you are looking for a solution, try implementing an approach similar to the following:


Object.values(val_funcs).forEach(function() {
  fn();
});

The Object.values function will list out all the values within the object. In case your file contains non-function elements, you can verify its type using the following code snippet:

.forEach(function(fn) {
  if(typeof fn === "function") 
    fn();
})

In situations where you need the values returned from the function, consider utilizing Array.map instead of forEach:


const values = Object.values(val_funcs)
                    .filter(function(fn) {
                      return typeof fn === "function";
                    })
                    .map(function(fn) {
                      return fn();
                    });

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

Deleting a key from a type in TypeScript using subtraction type

I am looking to create a type in TypeScript called ExcludeCart<T>, which essentially removes a specified key (in this case, cart) from the given type T. For example, if we have ExcludeCart<{foo: number, bar: string, cart: number}>, it should re ...

What is the process for creating a unit test case for an Angular service page?

How can I create test cases for the service page using Jasmine? I attempted to write unit tests for the following function. service.page.ts get(): Observable<Array<modelsample>> { const endpoint = "URL" ; return ...

Deactivate the button if the mat-radio element is not selected

Here is my setup with a mat-radio-group and a button: <form action=""> <mat-radio-group aria-label="Select an option"> <mat-radio-button value="1">Option 1</mat-radio-button> <mat-radio-b ...

What is the process for incorporating a custom action in TestCafe with TypeScript?

I've encountered an issue while trying to implement a custom action. When running tests with the new custom action, I keep receiving an error stating that my custom action is not recognized as a function. TypeError: testcafe_1.t.customActions.selectFr ...

Resolving Hot-Reload Problems in Angular Application Following Upgrade from Previous Version to 17

Since upgrading to Angular version 17, the hot-reload functionality has been causing some issues. Despite saving code changes, the updates are not being reflected in the application as expected, which is disrupting the development process. I am seeking ass ...

React | What could be preventing the defaultValue of the input from updating?

I am working with a stateful component that makes a CEP promise to fetch data from post offices. This data is retrieved when the Zip input contains 9 characters - 8 numbers and a '-' - and returns an object with the desired information. Below is ...

Utilizing Mongoose RefPath in NestJS to execute populate() operation

After registering my Schema with mongoose using Dynamic ref, I followed the documentation available at: https://mongoosejs.com/docs/populate.html#dynamic-ref @Schema({ collection: 'quotations' }) export class QuotationEntity { @Prop({ r ...

Adding an array into a MySQL database using PHP

My goal is to incorporate an array into my database. I've created a function that verifies if a value in the database (e.g. health and money) has been altered. If the value is different from the original, I update the new value in the $db array using ...

Using optional chaining with TypeScript types

I'm dealing with a complex data structure that is deeply nested, and I need to reference a type within it. The issue is that this type doesn't have its own unique name or definition. Here's an example: MyQuery['system']['error ...

The Angular 4 HTTP patch method is encountering difficulties when called in code but functions properly when tested using Post

My attempts to make a patch and post call to the server are failing as it never reaches the server. Interestingly, the same request works flawlessly in Postman, so I suspect there might be an issue with my code. Both my post and patch methods are essentia ...

What is the best way to retrieve the final value stored?

This is how I am using my Selector:- private loadTree() { this.loading = true; this.store.select(transitionListSelector).pipe().subscribe(data => { console.log(data); data.map(item => { console.log(item); this.tr ...

Efficient method for iterating through three arrays that have matching values and satisfy specified conditions in TypeScript

Struggling to speed up my Excel sheet creation time, currently taking over 20 seconds. I'm using the code below to compare three arrays and get the desired output: for (let i = 0; i < this.arrayNumberOne[0].length; i++) { let orangeOne = this.a ...

Nearly every category except for one from "any" (all varieties but one)

In Typescript, is it feasible to specify a type for a variable where the values can be any value except for one (or any other number of values)? For instance: let variable: NOT<any, 'number'> This variable can hold any type of value excep ...

Steer clear of using inline styling when designing with Mui V5

I firmly believe that separating styling from code enhances the clarity and cleanliness of the code. Personally, I have always viewed using inline styling (style={{}}) as a bad practice. In Mui V4, it was simple - I would create a styles file and import i ...

What is the abbreviation for indicating a return type as nullable?

Is there a way to use shorthand for nullable return types in TypeScript similar to using "name?: type" for parameters? function veryUsefulFunction(val?: string /* this is OK */) // but not this or other things I've tried. // is there a way a ...

Is it possible to create my TypeORM entities in TypeScript even though my application is written in JavaScript?

While I find it easier to write typeorm entities in TypeScript format, my entire application is written in JavaScript. Even though both languages compile the same way, I'm wondering if this mixed approach could potentially lead to any issues. Thank yo ...

The color scheme detection feature for matching media is malfunctioning on Safari

As I strive to incorporate a Dark Mode feature based on the user's system preferences, I utilize the @media query prefers-color-scheme: dark. While this approach is effective, I also find it necessary to conduct additional checks using JavaScript. de ...

How can I call a global function in Angular 8?

Currently implementing Angular 8, my objective is to utilize downloaded SVG icons through a .js library. To achieve this, I have made the necessary additions to my .angular.json file: "scripts": [ "node_modules/csspatternlibrary3/js/site ...

Tips for extracting HTML text with Python and Selenium

Utilizing Python's Selenium module, I am attempting to extract text and store it in a list or dataframe. Specifically, I am looking to retrieve the text "M" from a class named "flex". Once obtained, I want to input this along with another item into a ...

What is the best way to extract strings from a list based on an integer value?

How can I extract specific strings from a list using integers? I attempted the following method, but encountered an error: list = ['1', '2', '3', '4'] listlength = (len(list) + 1) int1 = 1 int2 = 1 while (int1 < ...