tips for accessing the output of a function within an object using TypeScript

I have developed a TypeScript module that simplifies the process. This function takes an object as input and executes all the functions while updating the values of the corresponding properties.

If any property in the object is not a function, it will be ignored during the process.

Below is the complete functional source code implemented in vanilla JavaScript, which needs to be converted into TypeScript:

import _ from 'lodash'

export default function flexifyParams(params) {
  const composedObject = {}
  for (const [key, value] of Object.entries(params)) {
    composedObject[key] = _.isFunction(value) ? value() : value
  }
  return composedObject
}

Here's an example showcasing how this function operates:

const test = {
  x: () => 'hi',
  y: () => 123,
  z: () => ['a', 'b', 'c'],
  a: 'my string',
}
const P = flexifyParams(test)

// The output for P would be:
//  {
//     x: 'hi',
//     y: 123,
//     z: ['a', 'b', 'c'],
//     a: 'my string',
//   }

I attempted to migrate this function to TypeScript by updating the code as follows:

import _ from 'lodash'

export default function flexifyParams<PARAMS extends object>(params: PARAMS): PARAMS {
  const composedObject: { [index: string]: string | Symbol | number } = {}
  for (const [key, value] of Object.entries(params)) {
    composedObject[key] = _.isFunction(value) ? value() : value
  }
  return composedObject as PARAMS
}

The above code works fine, but the function's return type needs adjustment.

While the keys of the returned object match those from the input parameter, their values are not identical; they are results from the respective functions.

How can I accurately define the return type for this function using TypeScript?

Answer №1

Considering that you are not specifying a return type and simply returning PARAMS, this declaration may not serve much purpose for your specific needs

I have decided to eliminate lodash from my solution because I do not prefer its usage


export default function flexifyParams<PARAMS extends object>(params: PARAMS): {
  [K in keyof PARAMS]: PARAMS[K]extends (...t: any) => infer R ? R :  PARAMS[K]
} {
  const composedObject: any = {}
  for (const [key, value] of Object.entries(params)) {
    composedObject[key] = typeof (value) === 'function' ? value() : value
  }
  return composedObject
}

Demo

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

Is it possible to retrieve the index of a chosen v-select option within Vuetify?

Exploring Vuetify for the first time, I'm encountering an issue with obtaining the index of a selected option on the v-select component. My goal is to populate a text field based on the option that is clicked once I have the index. I am fetching an ...

Organize array by year and month groupings

I'm trying to organize an array of events by year and month. Here is a sample of my data: const events = [ { name: "event 1", year: 2021, month: 1, }, { name: "event 2", year: 2021, month: 9, }, { ...

The error message "Property 'map' is not found on type 'User' in React with typescript"

I am currently experimenting with React using TypeScript. I have set up useState with an object but I am encountering issues trying to use the map function with that object. Below is the error message I am facing: Property 'map' does not exist ...

Calculate the total value of a specific field within an array of objects

When pulling data from a csv file and assigning it to an object array named SmartPostShipments [], calculating the total number of elements in the array using the .length property is straightforward. However, I also need to calculate the sum of each field ...

I am hoping for the outcome to be directed to the homepage

I'm struggling to figure this out, as I am new to classic ASP and JavaScript. I hope someone can help me understand. I want to display the response.write on the main.asp (or the result) page, but each time I try, it redirects to pass.asp on a differen ...

When using Sequelize, I encountered an error message from SQLite stating that the table does not exist despite having created

I am struggling to grasp the concept of how Sequelize operates and I can't figure out why I am encountering the SQLITE_ERROR: no such table: Users error even though I have created the table using sequelize.define. Here is my code: const { Sequelize, D ...

Enhancing NodeJS performance when manipulating arrays

I'm seeking a way to retrieve a user's chat history with other users from a separate collection in NodeJS and MongoDB. I have concerns about the potential performance impact of running the code below due to the nature of NodeJS. While I could d ...

AJAX reconstructs accordion elements and shatters them apart

I've implemented Search & Filter Pro to sort through images on a website. The checkbox filters are contained within accordions. Initially, everything functions correctly when the page loads. However, an issue arises when I click on a filter as it ...

The data sent within an event does not trigger reactivity

Not producing errors, just failing to function. The addition of this also has no impact. input( type="number" v-model="myData" @wheel="wheelIt($event, myData, myMethod)" ) ... methods: { wheelIt ( event, data, func ) { if ( event.deltaY ...

Is iterating over an array of objects the same as avoiding repetitive code?

Update: Incorporating JavaScript with the three.js library. To streamline our code and prevent repetition, we utilize loops. However, in this specific scenario, the for loop is not functioning as expected compared to six similar lines that should achieve ...

What is the best way to retrieve user interaction data in Discord.js v13?

Is there a way to retrieve the activities from interaction.options? Whenever I try using interaction.options.getUser, I encounter this error message: cannot read properties of undefined (reading 'activities') Below is the snippet of my code: con ...

The dynamics of Express.js functionalities

I am seeking to better understand how flow functions within an Express app using Routes, with the following set of Routes: app.use(require('./routes/reportsRouter')); app.use(require('./routes/crewsRouter')); app.use(require('./ro ...

"Unable to convert object into a primitive value" error message appears on Internet Explorer

Currently working on a webpage using Angular 7. The code is functioning perfectly in Chrome, however, I am facing an Exception error while running it in IE: An issue arises: Can't convert object to primitive value (polyfills.ts) The source of the er ...

How to dynamically modify a list box with JavaScript

I have an index.html file with a select tag containing multiple options for a drop-down: <label for="edu">Education</label> <select id="edu" name="edu"> <option value="0">10th</option&g ...

Deregister channel listener

My application has a functionality where users can subscribe to Twilio chat channels. When a user clicks on a channel, the chat opens up, messages are loaded, and the user is subscribed to receive new messages using this.state.channel.on('messageAdded ...

Horizontal rule located within a table but spanning the entire width

I wrote the following code: <table> {item.awards.map((obj,i) => <tbody> <tr> <td>Name</td> <td>:</td> <td>{obj.title}</td> </tr> ...

Including a hyperlink in VUE Bootstrap for seamless user navigation

Why does this always drive me crazy? I'm determined to include an external link () and an image(enter image description here) on my portfolio page within the title of the project. main.js { id: 18, url: 'single-portfolio. ...

Tips for simulating an axios request that returns an image buffer

I am attempting to simulate an axios api call that returns an image buffer as shown below: <Buffer ff d8 ff e0 00 10 4a 46 49 46 00 01 01 00 00 01 00 01 00 00 ff e1 00 de 45 78 69 66 00 00 49 49 2a 00 08 00 00 00 06 00 12 01 03 00 01 00 00 00 01 00 ... ...

Disregard the Field File when utilizing jQuery validation

I have created a form with jQuery validation, but I am facing an issue where the file upload field is showing a message "enter no more than 3 characters." I believe this problem is due to the maxlength="3" property in the file field. How can I remove the ...

Do devDependencies get installed when running `npm install -g my-package` command?

After browsing through this forum discussion, I found the answers a bit confusing and not directly addressing my concern. Therefore, I am posing a specific question: When using the command npm install -g my-package, are the dependencies listed under devDe ...