Creating a function generator using a string parameter in TypeScript

Is there a way to pass a string parameter to a function and retrieve an object with that key?

function getFunction(name: string): { [name]: () => number } {
  return {
    [name]: () => {
      console.log(1);
      return 2;
    },
  };
}

const { myName } = getFunction("myName");

I am interested in using TypeScript to generate hooks by endpoints property in rtk query createApi.

import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
import type { Pokemon } from './types'

// Defining a service with a base URL and expected endpoints
export const pokemonApi = createApi({
  reducerPath: 'pokemonApi',
  baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/' }),
  endpoints: (builder) => ({
    getPokemonByName: builder.query<Pokemon, string>({
      query: (name) => `pokemon/${name}`,
    }),
  }),
})

// Exporting hooks for functional components, which are
// automatically generated based on the defined endpoints
export const { useGetPokemonByNameQuery } = pokemonApi

Answer №1

Make sure you include name:string in the code.

function createFunction(name: string): { [name: string]: () => number } {
  return {
    [name]: () => {
      console.log(1);
      return 2;
    },
  };
}

const { myName } = createFunction("myName");

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

React native: Implementing a method to trigger an action upon entering a screen

Is there a way to trigger an action when a user visits a specific view in my application? I've tried using componentDidMount and componentWillMount but they don't seem to work for this purpose. If I include the action in the render method, it ca ...

Find the two numbers within a specific range in an array using jQuery

I have two arrays and I need to check for any duplicate ranges. How can I achieve this? let startingArray = ['1', '6.1', '10', '31','6.2',3]; let endingArray = ['2', '9.9', '30&ap ...

Using slashes in the import statement versus using require statement

Note: I am currently running on node version 14.1 Here is the line of code I'm experimenting with: import "module-alias/register"; This results in the following error: Error [ERR_MODULE_NOT_FOUND]: Cannot find module The error seems to point to t ...

Troubleshooting Node.js and Express: Adding to array leads to displaying "[object Object]"

As a newcomer to web development and currently enrolled in a course for it, I am in the process of creating a test web server before diving into my main project. In this test scenario, my goal is to extract the value from a text block and add it to a respo ...

What is the best way to trigger a function once all asynchronous calls within a loop have been completed?

The function addData is called asynchronously within a loop every time reader.onloadend is triggered. const uploadFiles = () => { console.log(acceptedFiles) setLoading(true) console.log(loading) let i = 0 let l = acceptedFiles.length ...

Redirecting clients on form submission from the client side

In my cshtml page, I have a script that calls a controller method via jQuery on form submission. It passes data to the method using the values from a datePicker control. Here's an example of the script: $('form').submit(function () { v ...

Steps to saving an item in the browser's local storage in real-time

My current challenge involves constructing a child array nested within a data array. When a user clicks on buttons to input data, the information does not get saved in localStorage in real-time. For example, if there are 4 buttons with different user input ...

What are some best practices for implementing TypeScript in a browser environment?

data-handler.js let users = [ { id: 1, name: "Alice", age: 25, active: true }, { id: 2, name: "Bob", age: 30, active: false }, { id: 3, name: "Charlie", age: 22, active: true }, { id: 4, name: "David", age: 28, active: false } ]; export { ...

Create a spectrum of vibrant colors depending on the numerical value

I'm attempting to create a function that generates rainbow colors based on a numerical value. var max = 10000; var min = 0; var val = 8890; function getColor(min, max, val) { // code to return color between red and black } Possible Colors: Re ...

Utilize the power of jQuery to make an ajax request to a PHP backend, expecting a response in JSON format. Then,

Having some trouble with my jQuery code when trying to parse a JSON object returned by PHP and create a list of hyperlinks. Despite receiving the JSON object, my list turns out empty. Can anyone assist me? Below is the jQuery code snippet and the JSON resp ...

Distinguishing keyboard and mouse events while focusing in React app

I have been working on implementing keyboard navigation focus outline for accessibility. The pseudo class :focus-visible works well on all elements except for input elements like text or textarea. It seems that inputs always have this pseudo class active s ...

Auto-complete feature not populating the input field in Google Chrome

Within my register form, I have various INPUT tags present. One of these INPUTs has the name email. <input type=text name=email id=email> When filling out this form in Chrome, I encounter a peculiar behavior. Upon clicking on the email input field ...

Angular is patiently awaiting the completion of the subscription

Currently, I am in the process of developing a test application using Angular. The challenge arises when I attempt to retrieve data through a Get request and then return a value based on that data. The code snippet below outlines the scenario: public getN ...

Seeking an efficient localStorage method for easy table modification (HTML page provided)

Currently, I am in the process of developing a custom 'tool' that consists of a main page with a menu and several subpages containing tables. This tool is intended for composing responses using prewritten components with my fellow colleagues at w ...

Ways to complete a progress bar up to 100% based on the user's specified time

I'm currently developing a progress bar for a pomodoro timer. The concept is for this bar to reach 100% completion based on the specified time of the pomodoro session. For instance, if the session is set for 30 minutes, the progress bar should be full ...

Adjusting the z-axis rotation in a three.js animated scene

Is there a way to add a function that changes the Z rotation value of the teapot from within the updateTeapot function? I came across this helpful answer on Three.js camera tilt up or down and keep horizon level. However, I am unsure how to integrate a z ...

The aspect ratio of an image is being calculated by loading the image twice

I am currently facing the issue where the same image is loading twice for a single preview. The first time the image is loaded for preview purposes in an iframe. The second time, the image metadata such as width and height are fetched with the same path. ...

Utilizing Jquery for independently blinking text counters

Whenever the user presses a button, a message is created and blinks 5 times. However, each time the button is pressed, all previous messages also blink along with the new one. The goal is to make only the new message blink individually 5 times upon each bu ...

Is there an alternative solution to the issue of the jQuery resize() event not triggering when an input is

Despite the fact that the jQuery event resize() should trigger when the width of an input box changes, it seems to be malfunctioning. As per the jQuery API documentation, the resize event is supposed to go to the (window) handler. So my query here is, what ...

What are the steps for removing rows of data with sequelize?

In my books.js Pug file, I have the following router where I am utilizing Sequelize ORM to find and delete a specific row of data based on the ID. /* - Removes a book. Be cautious, this action is permanent. Consider creating a "test" book for trial d ...