How to Extract the Specific Parameter Type from a Function in Typescript

After generating a client for an API using typescript-node, I encountered the following code:

export declare class Api {

    getUser(username: string, email: string, idType: '1298' | '2309' | '7801')

}

I need to access the type of the third parameter without having to define '1298' | '2309' | '7801' again in my application.

To achieve this, I used the following approach:

type idType = Parameters<Api['getUser']>[2];

However, I am not completely satisfied with this solution and would prefer to use the key 'idType' instead of its position as a parameter. Is there a way to accomplish this?

Any help or insights on this matter would be greatly appreciated. Thank you.

Answer №1

The current approach you are using is correct. I will now provide an alternative solution that involves some modifications for improved readability of the code structure.

function getUser(username: string, email: string, idType: '1298' | '2309' | '7801') { }

// Create utility types to enhance readability
type ArgName = 'first' | 'second' | 'third'
type ArgNum<T extends ArgName> =
    T extends 'first' ? 0 :
    T extends 'second' ? 1 :
    T extends 'third' ? 2 :
    0

type ArgumentType
    <F extends (...a: any) => any, N extends ArgName> =
    Parameters<F>[ArgNum<N>]

type A = ArgumentType<typeof getUser, 'third'>; // '1298' | '2309' | '7801'

In this modified version, we use descriptive keys instead of numeric values for better understanding. This can be especially useful for functions with multiple parameters where extending the keys is possible.

For your specific scenario, the implementation would appear as follows:

type IdType = ArgumentType<Api['getUser'], 'third'>; // '1298' | '2309' | '7801'

Answer №2

declare module Api {

    getProfile(firstName: string, lastName: string, userType: UserType)

}

export type UserType = 'student' | 'teacher' | 'administrator';

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

Combining various POST requests by matching the common value in each array. (Angular)

Here are the two different sets of data: "statusCode": 200, "data": [ { "color": { "id": "1111", "name": null, "hex&quo ...

Updating an object property within an array in Angular Typescript does not reflect changes in the view

I am currently delving into Typescript and Angular, and I have encountered an issue where my view does not update when I try to modify a value in an array that is assigned to an object I defined. I have a feeling that it might be related to the context b ...

Encountering difficulty importing TypeScript files dynamically within a Deno executable

When attempting to import a file from aws in an exe using its public link based on user input, I am facing difficulties For example, I generated my exe with the command below deno compile --allow-all main.ts Users execute this exe using commands like ./e ...

What are the best practices for preventing risky assignments between Ref<string> and Ref<string | undefined>?

Is there a way in Typescript to prevent assigning a Ref<string> to Ref<string | undefined> when using Vue's ref function to create typed Ref objects? Example When trying to assign undefined to a Ref<string>, an error is expected: co ...

A Typescript generic that creates a set of builder function interfaces

Consider a Typescript interface: interface Product { url: URL; available: boolean; price: number; } We need to create a generic type that can produce a builder type based on any given interface: interface ProductSteps { url: (data: unknown) => ...

Tips for altering a key within a tree-view:

I am working with a potentially infinite tree-view array: type Tree = { id: number; name: string; email: string; children: Tree[]; }; const tree: Tree[] = [ { id: 1, name: 'Truck', email: '@mail', children ...

Error: Module 'react' not found. Please make sure it is installed and correctly imported

Recently, I've been working on developing a React app using TypeScript. To kickstart the project, I used yarn create react-app (name) --use-pnp --typescript. However, I encountered an issue with the TS linter repeatedly showing the error: Cannot find ...

Injecting singletons in a circular manner with Inversify

Is it possible to use two singletons and enable them to call each other in the following manner? import 'reflect-metadata'; import { Container, inject, injectable } from 'inversify'; let container = new Container(); @injectable() cla ...

I am looking to append a new value to an array within the state in React

development environment ・ react ・ typescript In this setup, state groups are stored as arrays. If you want to add a group to the array of groups when the onClickGroups function is called, how should you go about implementing it? interface ISearc ...

create an instance of the class provided as an argument

I wanted to design a system for creating different types of Plants (inspired by plants vs zombies) in an organized way. To simplify the addition of new plant Types, I aimed to make the cost and damage of each plant static so it could be set once for all Pl ...

What is the correct way to invoke a static TypeScript class function in JavaScript?

Recently, I encountered a scenario where I have a TypeScript script called test.ts structured like this: class Foo { public static bar() { console.log("test"); } } The requirement was to call this TypeScript function from plain JavaScript ...

When using ngFor, a conversion from a string literal type to a regular string occurs, resulting in an error that states: "Element implicitly has an 'any' type because an expression of type 'string' cannot be utilized..."

When utilizing the iterator *ngFor, it converts a string union literal type ("apple" | "banana") to a string type. However, when attempting to use it as an index of an array expecting the correct string union literal type, an error occu ...

Pinia is having trouble importing the named export 'computed' from a non-ECMAScript module. Only the default export is accessible in this case

Having trouble using Pinia in Nuxt 2.15.8 and Vue 2.7.10 with Typescript. I've tried numerous methods and installed various dependencies, but nothing seems to work. After exhausting all options, I even had to restart my main folders on GitHub. The dep ...

Please ensure the subscription has completed before proceeding with the loop

I am currently working on an Angular application that retrieves data from an API and uses one of its parameters from a looped array. The issue I'm facing is that the data is pushed in a random order due to the continuous looping without waiting for th ...

Troubleshooting engine malfunction in Angular 9 caused by FormGroup usage

Here is a sample code snippet of a component: export class BaseFormComponent implements OnInit { basicFormGroup: FormGroup; constructor( protected basicProviderService: BasicProviderService, protected formBuilder: FormBuilder, protected di ...

Context failing to refresh value upon route changes

My current context setup is as follows: import { createContext, ReactNode, useState } from "react"; type props = { children: ReactNode; }; type GlobalContextType = { name: string; setName: (value: string) => void; }; export const Glob ...

What is the generic type that can be used for the arguments in

One function I've been working on is called time const time = <T>(fn: (...args: any[]) => Promise<T>, ...args: any[]): Promise<T> => { return new Promise(async (resolve, reject) => { const timer = setTimeout(() => r ...

What is the reason for restricting a placeholder for an optional property in the interface to only be of type any?

I am facing a challenge with a file containing a single declaration, which is for an interface: interface NamedPerson { firstName: string; age?: number; [propName: string]: any; greet(lastName: string): void; } Everything works perfectly ...

Pass on only the necessary attributes to the component

I have a simple component that I want to include most, if not all, of the default HTML element props. My idea was to possibly extend React.HTMLAttributes<HTMLElement> and then spread them in the component's attributes. However, the props' ...

Getting a string output from a Typescript promise

Here is some Typescript code that I thought would be simple. public showDialog(theNickname: string): string { var req = { method: 'POST', url: '/Q/GetUserDetails', data: { nickname ...