Determine the data type of a parameter based on the values of other parameters within the

Consider this function declaration:

function bar<E extends {}>(baz: Array<{ id: keyof E, data: any, additional: string}>): E[]

Let's also look at this interface:

interface F {
    g: boolean
    h: number
}

When calling bar with the following values:

bar<F>([{id: 'g', data: false, additional: 'extra'}, {id: 'h', data: 123, additional: 'bonus'}])

The goal is to properly infer the type of the second parameter data and avoid using any.

Any suggestions on how to achieve this?

Appreciate your help!

Answer №1

Implement mapped types to transform T into the desired format.

type NewType<T> = {
    [P in keyof T]: { key: P, value: T[P], otherParam: string }
}[keyof T];

Here is the complete solution:

type NewType<T> = {
    [P in keyof T]: { key: P, value: T[P], otherParam: string }
}[keyof T];

declare function transform<T extends object>(newType: NewType<T>[]): T[]

interface Example {
    a: string
    b: number
}

transform<Example>([{key: 'a', value: 'string', otherParam: 'other'}, {key: 'b', value: 100, otherParam: 'other'}])

TypeScript 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

The selectors in NgRx store are failing to retrieve data from the main global store

As I delve into the world of ngrx, I find myself struggling to fully understand and implement it effectively within my application. Recently, I integrated ngrx version 8.3 into my project in hopes of organizing my state management efficiently. My goal is ...

Enhanced interface with plugins

I've been developing a "manager" class that allows for the integration of "plugins". Each plugin has the ability to enhance the data property of the manager class. // manager.ts interface Data { // some props } class Manager { data: Data; ...

Error: Attempting to access 'update' property of a null value

function logUserOut(user: UserInstance) { return user.update({ token: null }); } I encountered an error at this part of the code. Any suggestions on how to fix it? ...

What is the most efficient method for incorporating React into Wordpress while using Typescript?

Is it possible for me to utilize the React / React-Dom scripts that Wordpress has enqueued in my bundled javascript, while still being able to use the -dev installed React for development purposes? The javascript files are designed for a WordPress plugin ...

In React and TypeScript, when I pass a state as a prop, the data fails to render

Here is the useState function for managing the Data Interestingly, removing this state from the code doesn't affect rendering at all. const [cart, setCart] = useState([] as Product[]); This piece of code handles Mapping and Rendering the Data <Sin ...

A step-by-step guide on extracting information from a component and using it within a Guard

A challenge I am facing is how to display a warning prompt on the screen if the user tries to leave a page after making changes to a form. I have successfully created a Guard that logs a message to the console when the user attempts to navigate away from t ...

Display or conceal columns in reaction to user choices with react-table in React with Typescript

I'm currently using react-table to create a data grid within my application. I have a specific requirement to show/hide columns based on user selection. Is there a way to accomplish this? Essentially, I need to implement a settings icon that, when cl ...

Typescript is throwing a fit over namespaces

My development environment consists of node v6.8.0, TypeScript v2.0.3, gulp v3.9.1, and gulp-typescript v3.0.2. However, I encounter an error when building with gulp. Below is the code snippet that is causing the issue: /// <reference path="../_all.d. ...

Having difficulty installing TypeScript on my machine

https://i.stack.imgur.com/l6COf.pngHaving trouble installing TypeScript with the following error: npm WARN registry Using outdated package data from https://registry.npmjs.org/ due to an error during revalidation. npm ERR! code E500 npm ERR! 500 Interna ...

Utilizing the spread operator in Typescript interfaces: best practices

I have a react component that includes the spread operator operating on ...other and passed down to lower levels of the component. interface ButtonProps { colourMode: string; regular: boolean; buttonText: string; disabled?: boolean; iconSize?: st ...

The issue of TypeScript failing to return HTML Template Element from Constructor typing is causing complications

There is a restriction on using new to create an instance of Template, which extends an HTMLTemplateElement. To work around this limitation, I fetch and return an HTMLTemplateElement by using document.getElementById(id) within the constructor of the Templ ...

I am looking to extract solely the numerical values

Programming Tools ・ react ・ typescript ・ yarn I am trying to extract only numbers using the match method But I keep encountering an error Error Message: TypeError: Cannot read property 'match' of undefined const age="19 years ...

Unlocking the Power of PropTypes.shape in TypeScript

Currently, I am in the process of migrating a React application from Javascript to Typescript. However, I am encountering difficulties, particularly with migrating the shape PropType. The code I have right now looks like this: import React from 'reac ...

Associate keys with strings and then map them to a specific type of strings in Typescript

I am endeavoring to develop a React component that extends the Octicons icon library available from Github at @githubprimer/octicons-react. One of the components exported by the library is the iconsByName type, which has the following structure: type ico ...

Exploring a JSON object using PlaywrightWould you like to know how

Greetings! Here is a snippet of code that I have, which initiates an API call to a specific URL. const [response] = await Promise.all([ page.waitForResponse(res => res.status() ==200 && res.url() == & ...

Ways to Access HTTP Request Headers in Angular 6 upon Page Load

Is it possible to retrieve request header information in Angular 6/7 upon application initialization? I specifically require access to header values for security and access management purposes, as these values are set in the headers during the usage of th ...

Implementing dynamic classes for each level of ul li using JavaScript

Can anyone help me achieve the goal of assigning different classes to each ul li element in vanilla Javascript? I have attempted a solution using jQuery, but I need it done without using any libraries. Any assistance would be greatly appreciated! con ...

Accessing collection values from referenced document IDs in Firestore---I have provided a unique version of the text

I have two fire store collections with the following reference images: https://i.sstatic.net/QVJkZ.pnghttps://i.sstatic.net/0QFRi.png. I am trying to retrieve the firstName and title from these collections. The signup_id is referenced from the document id ...

Understanding the Usage of FormData in NextJS

I'm trying to read fetch's body contents. Here's the code I'm using: fetch('/api/foo', { method: 'POST', body: new FormData(formRef.current), }); https://i.sstatic.net/6YB1V.png Now I need to parse the body dat ...

Addressing the reactivity issue when incorporating basic markdown directive into vuejs

In an effort to reduce dependency on vue-i18n formatting, I decided to create a simple Markdown formatter directive that only implements bold, emphasize, and strike-through styles. The current implementation of the directive is as follows: import _Vue ...