What is the TypeScript term for assigning multiple parameters an alias?

Imagine having a piece of code structured like this:

export async function execute(conf: Record<string, string>, path: string, params: Array<string>) {

    const cmd = params[1];
    const commandOption = params.slice(2)
    switch(cmd){
        case "param_1":
            return await function1(path, conf, commandOption)
            break;
        case "param_2":
            return await function2(path, conf, commandOption)
            break;
        case "param_3":
            return await function3(path, conf, commandOption)
            break;
        default:
            console.log("command not entered")
            break;
    }

}


async function function1(path: string, conf: Record<string, string>, params: Array<string>) {
    ...
}
async function function2(path: string, conf: Record<string, string>, params: Array<string>) {
    ...
}

..

The script defines the parameters with user input values and has similar functions with identical parameters. Is there a way to streamline this process and reduce redundancy by introducing an alias for all 3 parameters?

This could look something like:

alias allParameters = (path, conf, commandOption)

or even

alias allParametersFunc = (conf: Record<string, string>, path: string, params: Array<string>)

export async function execute(allParametersFunc) {

    const cmd = params[1];
    const commandOption = params.slice(2)
    switch(cmd){
        case "param_1":
            return await function1(allParameters)
            break;
        case "param_2":
            return await function2(allParameters)
            break;
        case "param_3":
            return await function3(allParameters)
            break;
        default:
            console.log("command not entered")
            break;
    }

}


async function function1(allParametersFunc) {
    ...
}
async function function2(allParametersFunc) {
    ...
}

...

Using objects might be one approach, but this method feels more intuitive akin to a yaml anchor.

Answer №1

One approach is to create an interface or type in advance that outlines the arguments and return types.

type FuncType = (config: Record<string, string>, path: string, parameters: Array<string>) => Promise<string>;

const function1: FuncType = (config, path, parameters) => {
  // ...
  return Promise.resolve('x');
};
const function2: FuncType = (config, path, parameters) => {
  // ...
  return Promise.resolve('x');
}

If the return types vary, you can make the function type generic instead and specify the return type during declaration:

type FuncType<T> = (config: Record<string, string>, path: string, parameters: Array<string>) => Promise<T>;

const function1: FuncType<string> = (config, path, parameters) => {
  // ...
  return Promise.resolve('x');
};
const function2: FuncType<number> = (config, path, parameters) => {
  // ...
  return Promise.resolve(5);
}

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

Learning how to use arrow functions with the `subscribe` function in

Can someone help clarify the use of arrow functions in TypeScript with an example from Angular 2's Observable subscribe method? Here's my question: I have code that is functional: this.readdataservice.getPost().subscribe( posts =&g ...

Tips for defining a distinct series of key-value pairs in typescript

Having experience with a different language where this was simple, I am finding it challenging to articulate a sequence of pairs: Each pair is made up of two basic elements (such as strings or numbers) Each element may appear multiple times within the lis ...

Tips for implementing UI properties in React

Utilizing an external UI Library, I have access to a Button component within that library. My goal is to create a customized NewButton component that not only inherits all props from the library Button component but also allows for additional props such as ...

Determining the data type of a property within an interface using TypeScript

Is there a way to extract the type from an interface based on its property name in order to use it in a Record? I am struggling with the syntax needed to retrieve the type by property name. My goal is to make this process more future-proof so that if the i ...

Angular 2 Component attribute masking

In my Angular 2 component called Foobar, I have defined a property named foobar: import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-foobar', templateUrl: './foobar.component ...

Can I retrieve the return type of useFetch in Nuxt3?

I am running into an issue while trying to specify the APIBody type in the following manner: Property 'test' does not exist on type 'NonNullable<PickFrom<_ResT, KeysOf>>'. It seems like there is no straightforward way to def ...

Determine if the "type" field is optional or mandatory for the specified input fields in Typescript

I need to determine whether the fields of a typescript type or interface are optional or required. export type Recommendation = { id?: string, name: string, type?: string, tt: string, isin?: string, issuer: string, quantity?: nu ...

Trouble with implementing a custom attribute directive in Angular 4 and Ionic 3

Hello, I am currently working on implementing a search input field focus using a directive that has been exported from directives.module.ts. The directives.module is properly imported into the app.module.ts file. However, when attempting to use the direc ...

Enhancing TypeScript builtin objects in Netbeans using a custom plugin

While in the process of converting JavaScript code to TypeScript, I encountered a challenge with extending built-in objects using Object.defineProperty, such as String.prototype. Object.defineProperty(String.prototype, 'testFunc', { value: funct ...

Separate the date format string into tokens

I am currently attempting to create a function that is able to transform a date format string such as %d/%m/%Y %H:%n where the variables are always denoted by a percentage sign followed by one character, into an array of tokens: ["%d", "/", "%m", "/", " ...

Exploration of narrowing union types in React with TypeScript

import { Chip } from "@mui/material"; type CourseFilterChipsRangeType = { labels: { from: string; to: string }; values: { from: number; to: number }; toggler: (from: number, to: number) => void; }; type CourseFilterChipsCheckType = { ...

Altering or including new space variables within a custom Chakra-ui theme

Looking to customize spacing variables in a Chakra UI theme? I have successfully implemented various extensions, but changes to spacing are not being applied. const config: ThemeConfig = { initialColorMode: 'light', useSystemColorMode: false ...

App that uses Angular 2 for real-time data refreshing

As a newcomer to Angular and Nodejs, I am venturing into the development of a MEAN stack cryptocurrency exchange application. My approach involves setting up a nodejs backend to retrieve the current exchange rate from an API and presenting it in the HTML. ...

The issue of excessive recursion in Typescript

Currently, I am in the process of learning Typescript while working on some exercises. While attempting to solve a particular problem, I encountered an error related to excessive recursion. This issue arises even though I created wrapper functions. About ...

Handling exception type in child_process exec method - NodeJS with Typescript integration

Check out this sample code: const execPromise = util.promisify(exec); try { const { stdout } = await execPromise(cliCommand); } catch (error) { if (error instanceof S3ServiceException) { // error message is not handled correctly console ...

Ways to specify the type signature for objects that incorporate a fresh method

My understanding is that in TypeScript, we use new() to structurally type a class constructor. But how do we type an object that includes a new method, for example: const k = { new() { return '123' } } ...

To close the Muix DateTimePicker, simply hit the Escape key or click anywhere outside of the picker

I'd like the DateTimePicker to only close when the user presses the action buttons, not when they click outside or press Escape. Unfortunately, I haven't found any props to control this behavior yet. <DesktopDatePicker closeOnSelect={false} s ...

Exploring Typescript within React: Creating a property on the current instance

Within my non-TypeScript React component, I previously implemented: componentWillMount() { this.delayedSearch = _.debounce((val) => { this.onQuerySearch(val); }, 1000); } This was for debouncing user input on an input field. The corres ...

Is it possible to use Date as a key in a Typescript Map?

Within my application, I have a requirement for mapping objects according to specific dates. Given that typescript provides both the Map and Date objects, I initially assumed this task would be straightforward. let map: Map<Date, MyObject> = new M ...

Experiencing Typescript errors solely when running on GitHub Actions

I've been working on a React+Vite project with the Dockerfile below. Everything runs smoothly when I execute it locally, but I encounter errors like Cannot find module '@/components/ui/Button' or its corresponding type declarations and error ...