Is it feasible to obtain the parameter types of a function in Typescript?

Illustration:

function a(...args: ???type of b() params???) {
  b(...args)
}

The goal is for args to match the type of parameters in function b.

This idea is aimed at improving code readability and encapsulation. The function b is imported, so I don't need to worry about its implementation when declaring function a.

Answer №1

If you want to achieve this functionality, the solution lies in version 3.0 with the introduction of Tuples in rest parameters and spread expressions (currently in RC phase)

type ArgumentType<T> = T extends (...args: infer U) => any ? U : never;

function a(...args: ArgumentType<typeof b>) {
    function b(...args: any[]) {

    }
}
// Demonstrating more complex examples
function a2(...args: ArgumentType<typeof b>) {
    function b(name: string, value: number) {

    }
}

a2("", 1);

Answer №2

This provides an alternative approach:

function customFunction(...input: Parameters<typeof targetFunction>) {
  targetFunction(...input);
}

playground link

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

Ways to increase the number of responses in an Express app after the initial response

In order to comply with the Facebook messenger API requirements, a 200 response must be sent immediately upon receiving the webhook request on my server, within 20 seconds. However, this process may take longer than the execution time of other middleware f ...

Errors in TypeScript type definition IntelliSense

While using Visual Studio 2022, I am encountering numerous IntelliSense errors related to type definitions from the node_modules folder appearing in the error list window. I have already excluded the node_modules folder in my tsconfig.json file like this ...

How to Remove onFocus Warning in React TypeScript with Clear Input Type="number" and Start without a Default Value

Is there a way to either clear an HTML input field of a previous set number when onFocus is triggered or start with an empty field? When salary: null is set in the constructor, a warning appears on page load: Warning: The value prop on input should not ...

Mastering the art of typing Vuex modules in Vue 3 with TypeScript

I've been grappling with how to properly type vuex modules in a Vue 3 TypeScript project. The official documentation doesn't provide much guidance on this topic. Let's say I have a setup like this: import { createStore, useStore as baseUseS ...

Angular2/TypeScript Coding Guidelines

I am curious about the common practices and consensus among the Angular2 community when it comes to writing reusable code in TypeScript. I have gathered some information and questions related to Angular2 that I would like to discuss. Organizing Module/A ...

Tips for utilizing the `tsconfig.js` file in place of the `tsconfig.json` file

I have several projects each with their own tsconfig.json files and other configuration files, and my aim is to use the same configurations across all of them. To accomplish this, I decided to create an npm package called config, which contains a standard ...

Trigger the D3 component to re-render in React after a state change occurs in the parent component

My React project consists of two components written in TypeScript. The first component contains menus, and I am using conditional rendering to display different content based on user selection. <Menu.Item name="graph" active={activeItem ...

React-snap causing trouble with Firebase

I'm having trouble loading items from firebase on my homepage and I keep running into an error. Does anyone have any advice on how to fix this? I've been following the instructions on https://github.com/stereobooster/react-snap and here is how ...

Utilizing Typescript Generics in Arrow Function to Combine Two Arguments

For instance, I am working with this code in a .tsx file extension const Add = <T,>(arg0: T, arg1: T): T => arg0 + arg1; const A = Add(1, 2); const B = Add('1', '2') However, I am encountering an issue, as there is an error m ...

GlobalsService is encountering an issue resolving all parameters: (?)

I am currently working on implementing a service to store globally used information. Initially, the stored data will only include details of the current user. import {Injectable} from '@angular/core'; import {UserService} from "../user/user.serv ...

Having trouble processing images in multi-file components with Vue and TypeScript

Recently, I reorganized my component setup by implementing a multi-file structure: src/components/ui/navbar/ Navbar.component.ts navbar.html navbar.scss Within the navbar.html file, there was an issue with a base64-encoded image <img /> ...

Transferring client-side data through server functions in Next.js version 14

I am working on a sample Next.js application that includes a form for submitting usernames to the server using server actions. In addition to the username, I also need to send the timestamp of the form submission. To achieve this, I set up a hidden input f ...

Issue: Angular2 RC2 throwing an error "No provider for DirectiveResolver!" while attempting to utilize TestComponentBuilder during a unit test

I have encountered an issue while trying to test my angular2 application. Every time I import TestComponentBuilder, it throws an error: Error: No provider for DirectiveResolver! This project is written in TypeScript and uses Angular2 RC2. Below is the co ...

Querying with Node SQLite fails to return a value

So, here's my little dilemma: I have 3 methods that need to access a database file (SQLite3). export function F_SetupDatabase(_logger: any): void export function Q_RunQuery(query: string, db: "session" | "global"): any export func ...

Create a class with additional attributes to support different types of options

I define a set of options represented by strings: export type Category = 'people' | 'projects' | 'topics' | 'tools' An index is declared as follows: interface Entry { ... } type IPostEntryIndex = { [name in Cate ...

How can Karma unit tests with Jasmine in a TypeScript Node project accurately measure code coverage, even with external dependencies?

We have a unique situation with the code coverage of our project involving a node dependency. It's important to note that the npm dependency source code is actually part of our project, as we are responsible for its development and publication. Here&a ...

Having trouble moving to a different component in Angular?

In my application, I am facing an issue with navigating from List to Details component by passing the ID parameter. It seems that there is no response or error when attempting to call the relevant method. Below, you can find the code snippets related to th ...

Problem with custom anchor component in React that needs to perform an action before being clicked

React Component (Custom Anchor) import React from 'react'; class Anchor extends React.Component { onClick = (event) => { // ----------------------------- // send Google Analytics request ...

Tips for altering the color of the MUI table sort label icon:

Does anyone know how to change the color of the table sort label icon from gray to red? I am having trouble figuring it out. Any recommendations or suggestions would be greatly appreciated. Here is the code I have been trying to work with: <TableSortL ...

Is there a way to interrupt the routerLink function when a user is prompted in Angular 4+?

I am seeking to replicate the traditional functionality found in HTML where clicking a link triggers a confirmation pop-up before being redirected: <a href='http://www.example.com' onclick="if ( window.confirm ('Are you sure you want to ...