Change the TypeScript type of the list in order to generate a type with key-value pairs

While experimenting with TypeScript type manipulation, I attempted to modify the type provided below

type setOfFunctions = [{
    name: 'hi',
    fun: () => number
}, {
    name: 'world',
    fun: () => string
}]

in order to achieve the following desired type

type MyFunctions = {
    hi: () => number,
    world: () => string
}

I made an attempt using the following type

type MyFunctions = {
    [key in setOfFunctions[number]["name"]] : setOfFunctions[number]["fun"]
}

However, this resulted in

type MyFunctions = {
    hi: (() => number) | (() => string);
    world: (() => number) | (() => string);
}

Answer №1

The current setup makes it so that

setOfFunctions[number]["fun"]
combines both types into one, requiring some filtering.

Here is a solution:

Employing a "filter" with a generic and an extends operation, the type of the function can be inferred when there's a match for the key. If no match is found, the function type is discarded using never.

type setOfFunctions = [{
    name: 'hi',
    fun: () => number
}, {
    name: 'world',
    fun: () => string
}]

type getPropertieFnType<T extends setOfFunctions[number], key extends string> = T extends { name: key, fun: infer K } ? K : never

type MyFunctions  = {
    [key in setOfFunctions[number]["name"]]: getPropertieFnType<setOfFunctions[number], key>
}

Playground

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

Retrieve the state using a custom hook in a different location

My custom hook is designed to retrieve and parse a JSON object from the DOM like this: export const useConfig = () => { const [config, setConfig] = useState<Config>(); useEffect(() => { if (document) { const config ...

Incorporating aws-sdk into Angular 2 for enhanced functionality

I'm currently working on integrating my Angular2 application with an s3 bucket on my AWS account for reading and writing data. In the past, we used the aws-sdk in AngularJS (and most other projects), so I assumed that the same would apply to Angular2 ...

Why is the input box not opening when I click on the edit icon?

Whenever the edit button is clicked, the input box does not open. After clicking on the edit option and then clicking on another input box, it will be changed to an input box. I want the input box to change when the edit option is clicked. ...

Oops! Your file couldn't make it to Firebase Storage in Angular

I have been working on creating an upload function to upload files or images to my Firebase database storage. I have ensured that the correct API key is placed in the environment.ts file and imported into app.module.ts as AngularFireModule.initializeApp(en ...

Utilizing an API to dynamically augment a JSON object with user input in Angular

Hello, I am working on adding an input value to an object property. The scenario is that a customer wants to add an item to their shopping cart, but before adding the item, they need to choose the size. I have the form set up with validation and can retri ...

Typescript: Utilizing Index-Based Callback Parameters in Functions

I am currently working on creating a function that can handle specific data types ("resource") along with an array of arrays containing call objects and corresponding callbacks for when the calls finish ("handlers"). function useHandleResource< R exte ...

In order to work with Mongoose and Typescript, it is necessary for me to

I am currently following the guidelines outlined in the Mongoose documentation to incorporate TypeScript support into my project: https://mongoosejs.com/docs/typescript.html. Within the documentation, there is an example provided as follows: import { Sche ...

Can someone explain how to showcase a collection attribute in Angular?

I am working with a collection of objects called "ELEMENT_DATA". Each object in the collection has an attribute named "Activite", which is also a collection. My goal is to display this attribute in a specific way. Below is my app.component.ts: export cla ...

How can you determine the type of an argument based on the type of another argument?

Is it possible to dynamically assign value types in the const set = (key: keyof Store, value: any) function based on the keys defined in the Store interface? For instance, setting a key foo as type number and key bar as type string[]. import store from & ...

What methods can I implement to enhance the capabilities of my API when my response types are defined as interfaces?

My React application requires an extension method to be added on the Product type in order to make refactoring easier. This extension method should include boolean checks such as product.hasAbc() that references the attributes property. Currently, the API ...

Adjust the size of the plane in Three.js to match the entire view

English is not my strong suit, as I am Japanese. I apologize for any confusion. Currently, my focus is on studying Three.js. I aim to position a Plane directly in front of the camera as the background. My goal is to have the Plane background fill the en ...

Creating nested objects in Javascript involves adding an object inside another object

There are two objects that I have: obj1= { '201609': 52, '201610': 54, '201611': 56, metric: 'promotionsOut', careerLevelGroups: [ { '201609': 52, &a ...

Using useRef as a prop in React with TypeScript

I am currently experimenting with TypeScript and encountering an issue when trying to use useRef in a custom element specifically when passing it as a prop I have attempted the following: import React from "react"; export interface InputProps extends ...

Expectation in Observable: Unable to provide data retrieval

In my Angular 7 and Typescript project, I am faced with the challenge of reading a json file from within a zip file. Although I am able to successfully display the correct json output on the console, I am struggling to return this json data from the functi ...

What is the significance of an equals sign being located within the angle brackets of a type parameter?

Within the type definitions for Bluebird promises, there is a catch function that has the following definition: catch<U = R>(onReject: ((error: any) => Resolvable<U>) | undefined | null): Bluebird<U | R>; The symbol "R" is derived fr ...

Ways to break down a collection of multiple arrays

Looking to transform an array that consists of multiple arrays into a format suitable for an external API. For example: [ [44.5,43.2,45.1] , [42, 41.2, 48.1] ] transforming into [ [44.5,42], [43.2,41.2] , [45.1, 48.1] ] My current code attempts this ...

Creating a HandleCredentialResponse function in Angular version 14 for implementing the "Sign in with Google" feature using Typescript

In the process of building a very simple angular version 14 application, I am working on displaying a 'Sign in with Google button' and incorporating the login functionality. For information about the new method of Sign in With Google, you can re ...

Creating and updating a TypeScript definition file for my React component library built with TypeScript

As I work on developing a React library using TypeScript, it is important to me that consumers of the library have access to a TypeScript definition file. How can I ensure that the TypeScript definition file always accurately reflects and matches the Java ...

How come I lose a day when attempting to convert a date to an ISO string in JavaScript?

I've been attempting to convert a date object to the ISOString() format, but it's consistently returning a result that is 1 day off (i.e., it subtracts 1 day). var fromDate = { day:4, month:5, year:2012 } var fromDateString = new Date ...

Using Angular 2 global pipes without requiring PLATFORM_PIPES

I was interested in utilizing a feature to create a global pipe and came across this link: https://angular.io/docs/ts/latest/api/core/index/PLATFORM_PIPES-let.html However, I discovered that it is deprecated with the following message: Providing platform ...