Can the output type of a function be dynamically determined by using the function parameter name as the property in an interface?

I am attempting to dynamically assign the output of a function based on the name of the input parameter within an existing interface:

interface MyInterface {
  typeA: string;
  typeB: boolean;
  typeC: string;
  typeD: number;
  ...
}

const myFunction: (parameterName: string) => MyInterface[parameterName] =
  (parameterName) =>
    {
      ...
      return valueXYZ 
    }

An error is appearing that states:

'parameterName' refers to a value, but is being used as a type here.

Currently, the variables defined in this manner must each implement their specific type individually, preventing me from typing my function in a more general way as envisioned above.

const valueA: MyInterface['typeA'] = myFunction('typeA');
const valueB: MyInterface['typeB'] = myFunction('typeB');
const valueC: MyInterface['typeC'] = myFunction('typeC');
const valueD: MyInterface['typeD'] = myFunction('typeD');
...

Is there a method to instruct Typescript to utilize the parameterName as the propertyName defined in the interface?

Answer №1

To ensure that your function's output value is determined by a parameter, you can utilize the following approach:

interface MyCustomInterface {
  category: string;
  isActive: boolean;
  price: number;
  quantity: number;
}

const customFunction = <T extends keyof MyCustomInterface>(paramName: T): MyCustomInterface[T] => {
  ...implementation
}

const result1 = customFunction('isActive'); // typeof result1 is boolean
const result2 = customFunction('quantity'); // typeof result2 is number
const result3 = customFunction('unknown'); // error, 'unknown' is not in MyCustomInterface

Answer №2

interface Widget {
   foo: Foo;
   bar: Bar;
}

function newWidget<T extends keyof Widget>(parameter: T): Widget[T] {
  ...
}

const foo = newWidget('foo');
// foo: Foo
const bar = newWidget('bar');
// bar: Bar

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

Exploring the power of Node JS with Promise.all and forEach within a nested array

When working on a Node app with typescript, I encountered the need to iterate through an array while calling an asynchronous function inside the loop to fetch information about related items for each item in the array. The function is called for each relat ...

How to access a variable from one page to another in Ionic version 3

Is it possible to use a variable declared within a function in another page? Here's the scenario: On the home page, I capture an image using the following code: capture(event, fab: FabContainer) { fab.close(); const cameraOptions: CameraOptions = { ...

Guide to implementing a dropdown menu for selecting countries in Angular

Recently, I was involved in an ecommerce project that required a login feature with a country code selection option for mobile users. I'm currently using Angular 7 for this project and was wondering if there are any packages available that can provide ...

What is the appropriate event type to pass to the onKeyPressed function in a React application utilizing MaterialUI and written with Typescript?

I am currently working on a React application using Typescript and MaterialUI, where I have implemented a TextField component. My goal is to capture the value of the input HTML element when the user presses the enter key. To achieve this, I have created ...

Guide to importing OBJ file into three.js using TypeScript

Currently, I am utilizing TypeScript along with three.d.ts obtained from definitely typed. While I have successfully been using THREE.JSONLoader, I am encountering difficulties with implementing an OBJLoader from here in a TypeScript project. It seems th ...

The raw password value must be provided and cannot be left blank

I am currently learning Java Springboot and working on creating a todo app with React (TypeScript) and Springboot. As I attempt to signup, an error occurs stating "rawPassword cannot be null" from Springboot. My frontend is running on localhost:3000 and b ...

What steps are needed to generate a production version of a TypeScript monorepo application that can be deployed to an Azure Function App?

I've been grappling with understanding Typescript project references and their intended use in a production build, especially for an Azure Function App. I'm not utilizing any monorepo functionality at the package manager level, such as npm worksp ...

typescript leaflet loading tutorial

I'm attempting to replicate the basic example of loading a map with Leaflet in TypeScript, following the guidance on the Leaflet website. I am not utilizing any frameworks like Angular or React. I have installed Leaflet and types through npm. To adher ...

The attribute 'disabled' is originally defined as a characteristic within the class 'CanColor & CanDisableRipple & HasTabIndex & MatChipBase'. However, it is replaced in the current context of 'MatChip' as an attribute

After updating my Angular version from 9.1 to 11, I encountered a compilation error. Error: node_modules/@angular/material/chips/chips.d.ts:120:9 - error TS2611:'disabled' is defined as a property in class 'CanColor & CanDisableRipple &a ...

Can you explain how the "reduce" function can be implemented using an interface in TypeScript?

Can you explain the "reduce" function using an interface in TypeScript? https://i.stack.imgur.com/X1VxL.png ...

Angular model-based forms encounter an issue with converting null to an object during asynchronous validation

In my Angular app, I'm working on implementing async validation for a model-based form. I've simplified the form by removing other fields for clarity, but there are additional fields in the actual form. The goal is to check if a username is uniqu ...

Using node.js to set the billing address while confirming a Stripe Payment intent

Is there a way to specify the billing address of a payment intent with Node.js? When using the Stripe.js browser-side framework, I can easily accomplish this by utilizing Stripe elements and the stripe.confirmPayment function, which automatically captures ...

What is the best way to showcase the information retrieved from my API?

I am attempting to display the ID and Document number that are retrieved from an array. Data Returned However, I am not seeing any results in return. You can view the application results here. I have tried using string interpolation like {{document.id}} ...

Failed to update the innerHTML attribute for the anchor tag

I'm attempting to apply styles through DOM manipulation using Angular's renderer2. I have successfully updated styles for all HTML elements except for anchors. In the example below, I am trying to replace the text www.url.com with World within ...

When a Vue component collapses on itself, it prevents the next component from rendering

Within my primary component, known as App.vue, I have structured the template code like so: <template> <div class="app-wrapper"> <Header></Header> <Panel></Panel> <Showcase/> <Modal/> < ...

Using Typescript for-loop to extract information from a JSON array

I'm currently developing a project in Angular 8 that involves utilizing an API with a JSON Array. Here is a snippet of the data: "success":true, "data":{ "summary":{ "total":606, "confirmedCasesIndian":563, "con ...

Employing async/await for efficient data retrieval

Attempting to utilize async-await in TypeScript Vue 3 to retrieve data, but encountering an issue where the function is already logging 'undefined' (or executing before the function call) private async exportDataOrder() { await this.getDataEx ...

When executing the release command in Ionic 3, the Angular AoT build encountered a failure

Struggling to get my Sony Z2 smartphone app running. Command used: ionic build android --prod --release Error displayed in console: typescript error Type CirckelmovementPage in C:/Users/fearcoder/Documents/natuurkundeformules/src/pages/cir ...

Do const generics similar to Rust exist in TypeScript?

Within TypeScript, literals are considered types. By implementing const-generics, I would have the ability to utilize the value of the literal within the type it belongs to. For example: class PreciseCurrency<const EXCHANGE_RATE: number> { amount ...

Utilizing Typescript for Efficient Autocomplete in React with Google's API

Struggling to align the types between a Google address autocomplete and a React-Bootstrap form, specifically for the ref. class ProfileForm extends React.Component<PropsFromRedux, ProfileFormState> { private myRef = React.createRef<FormContro ...