Change the object's data type while preserving the connection between keys and values

Imagine having a defined object type, for example:

interface A {
  foo: string;
  bar: number;
  baz: boolean;
  // …
}

Is there a way to use a generic type to completely change its structure while maintaining the key-value relationship?

One possibility could be to create { key, value } objects like this:

type KeyValueObject =
  | { key: 'foo'; value: string; }
  | { key: 'bar'; value: number; }
  | { key: 'baz'; value: boolean; }
// | …

Alternatively, you could define a function that takes in these key-value pairs as arguments:

type KeyValueHandler =
  | (key: 'foo', value: string) => Promise<string>
  | (key: 'bar', value: number) => Promise<number>
  | (key: 'baz', value: boolean) => Promise<boolean>
// | …

I initially thought that mapped types might provide a solution, but I couldn't quite grasp how to apply them in this scenario.

Answer №1

Mapped types are truly a game-changer - the information provided in this resource really helped me understand.

By utilizing a mapped type alongside a property lookup, you can achieve impressive results.

type Dictionary<T> = {
  [K in keyof T]: { key: K; value: T[K] };
}[keyof T];

// just for illustration purposes - the outcome may not be practically useful
type AsyncKeyValueTransform<T, R> = {
  [K in keyof T]: (key: K, value: T[K]) => Promise<T[K]>;
}[keyof T];

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

What is the reason behind Rxjs switchMap only emitting the final value from an of() observable source?

Here are two code snippets, one using map and the other using switchMap. The functionality of map is clear: of('foo', 'bar') .pipe(map((val) => sanitizer(val))) .subscribe((val) => console.log('value:', val)); func ...

Using TypeScript - Implementing Reduce function with a return type containing optional fields

I am facing challenges in satisfying the TypeScript compiler with my code. I define a type that includes only optional fields, for example: interface UserData { email?: string; phone?: string; //... } and I have a reduction function that transforms ...

What is the process for manually testing a TypeScript function within a React application?

Hey there, I have a question as a beginner. I am currently using React and TypeScript with create-react-app, and I have some JavaScript code that is not related to the user interface (it's a module for working with a REST API). Here is an example of w ...

Angular 6 - Build a dynamic single page housing various applications within

I am faced with the task of developing multiple applications using Angular 6. Each application will have its own set of components, services, and more. However, there is also a need for shared services, components, directives, and other elements that will ...

Searching for data based on specific keywords in Angular 2, rather than using a wildcard search, can be done by utilizing the key-in

My dropdown contains 100 values, and I am currently able to search for these values based on key input using wild search. However, I would like the dropdown to display values based on the specific alphabet that I enter first. HTML: <div class="col- ...

The Observable<ArrayBuffer> type does not have a property map

I encountered an issue while upgrading from Angular v4 to Angular v6. I was in the process of replacing Http and HttpModule with HttpClient and HttpClientModule. As a result, I imported HttpClient from @angular/common/http in a service to fetch results fro ...

What is the reason for not applying type guards to callback function arguments?

Check out this TypeScript code snippet for a quick example. // Setting up the example declare var data:{info?: {details: string}}; function instant(callback: () => void) { callback(); } // Safeguarding the data if (data.info) { console.log(data.inf ...

The width of the Ion-slide is dynamically determined by the styling

After transitioning my Ionic 2 project to Ionic 3, I encountered issues with ion-slides which are affecting my app's functionality. Upon app loading, specific widths are being defined in the style tags on the slides, disrupting the intended styling. ...

Can a function utilize a Generic-specified type property?

function extractStringValue<T extends object, S extends keyof PickByValue<T, string>>( obj: T, key: S ): string { return obj[key]; }; The PickByValue function extracts properties of object T with values of type string. type CustomType = ...

Discovering the Error Message within the Error Object transmitted by NodeJS to Angular

When handling errors in Nodejs functions using a try/catch scope, an error may be returned in cases such as when the user doesn't exist or when the database is unreachable. The code snippet below demonstrates this scenario: router.delete('/delete ...

Discovering the process of iterating through values from multiple arrays of objects and applying them to a new response in Angular 8

Received the following data from an API response: const apiResponse = { "factoryId": "A_0421", "loss": [ { "lossType": "Planned Stoppage Time", "duration": ...

When working with TypeScript in Node, the module ""http"" does not have a default export available

const httpModule = require('http'); httpModule.createServer((req, res) => { res.end('Hello World'); }).listen(3000, () => console.log('Server is running on port 3000')); I've installed @types/node but ...

The statement "import React from 'react'" is automatically removed by VS Code

When I need to remove unused modules that I no longer need, I frequently use shift + alt + o. This method has worked perfectly for me in the past when editing .tsx files. However, recently, VS Code seems to be removing the import React from 'react&ap ...

Can you explain the meaning of the code snippet: ` <TFunction extends Function>(target: TFunction) => TFunction | void`?

As I delve into the contents of the lib.d.ts file, one particular section caught my attention: declare type ClassDecorator = <TFunction extends Function>(target: TFunction) => TFunction | void; The syntax in this snippet is a bit perplexing to m ...

Convert TypeScript interface property types to unions

I am in possession of an interface that holds keys of various types, and I am interested in creating a new type based on the types of those keys. interface SomeType { abc: string; def: number; ghi: boolean; } The type I want to create: type SomeOthe ...

Navigating to the detail page following a POST request in RTK query: A step-by-step guide

In my React RTK-query form, I am facing an issue where after a POST request is made, the form should navigate to the next step. However, in order to do that, I need to obtain the id of the newly created record. The backend auto-increments the id and does n ...

Unable to employ the inequality operator while querying a collection in AngularFire

I'm facing a challenge with pulling a collection from Firebase that is not linked to the user. While I've managed to query the user's collection successfully, I am struggling to retrieve the collection that does not belong to the user using ...

Managing background tasks with Node.js in real-time

I am currently faced with the challenge of managing background events. When a user is temporarily banned, we save the ban expiration in our database to ensure they are unbanned at the right time. However, my current code checks every ban every 10 seconds ...

I find it strange that this warning message continues to pop up even though there is already a key prop assigned. It keeps saying: "Each child in a list should have a unique 'key'

As a newcomer to React, I find myself puzzled by the recurring appearance of this warning message: Warning: Each child in a list should have a unique "key" prop Even though there is already a key prop present on the element, why does this warn ...

Error message: Cordova not found - unable to use 'ionic native' 3 for CRUD operations with SQLite database

I am attempting to manage CRUD data with SQLite in Ionic 3, but unfortunately cordova is not functioning as expected. https://i.sstatic.net/5m411.png ...