Is it possible for TypeScript to convert objects while preserving type annotations?

Apologies for my limited English skills, but I will do my best to explain my dilemma.

I am looking to create a TypeScript function that can replace the keys of an Object.

For example:

interface Target {
    name: string;
    ID: number;
}

// The function
function objectAdapter<T extends Object, K extends keyof T>(
    data: T,
    transformMap: Record<keyof Target, K>
) {
    return Object.keys(transformMap).reduce((p, c) => (p[c] = data[transformMap[c]], p), {})
}

const result = objectAdapter({ nickname: 'link', id: 123456 }, { name: 'nickname', id: 'ID' });

The code above allows me to achieve the following transformation:

// Transforming data from
{
    nickname: 'link',
    id: 123456
}
// To
{
    name: 'link',
    ID: 123456
}

However, when filling in the values of `transformMap`, my IDE did not provide correct suggestions.

Moreover, all properties of the `result` are inferred as 'string|number', whereas I would like them to be similar to the `Target` interface.

Thank you for reading and anticipating your support. Thank you♪(・ω・)ノ.

Answer №1

In my opinion, it is essential to define a mapped type that accurately enforces the mapping types and then utilize it within your objectAdapter() function while specifying the return type.

For instance:

interface Target {
    name: string;
    ID: number;
}

type KeyMap<T> = {
    [P in keyof T]: keyof Target;
};

function objectAdapter<T extends Record<string, any>, K extends KeyMap<T>>(
    data: T,
    map: K
): Target {
    return Object.keys(map).reduce((prev, current) => {
        prev[map[current]] = data[current];
        return prev;
    }, {} as Target);
}

const processedData = objectAdapter({ nickname: 'link', id: 123456 }, { nickname: 'name', id: 'ID' });

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

Encountering errors in Visual Studio when trying to work with node_modules directories that have a tsconfig

In my current project, there is a tsconfig.json file located in the root directory. Strangely, Visual Studio keeps throwing errors related to other instances of tsconfig.json found in different packages, as shown below: https://i.sstatic.net/T7Co2.png Ev ...

Issues encountered when attempting to add a new user on Firebase

I am facing an issue with this function that is supposed to add new users to my firebase database, but for some reason, it's not working. exports.createUserWithEmailAndPassword = functions.https.onCall( async(data, context) => { const { ...

How come a null variable continues to widen to type any even when strictNullChecks is enabled?

According to the TypeScript Documentation, if strictNullChecks is true, there should be no type widening. Also, the typeof nul should be null. let nul = null; // typeof nul = any let undef = undefined; // typeof undef = any Check it out in the Playground ...

Employing multiple subscriptions within a function

I am facing an issue in my Angular application where I am trying to display a detailed summary of the sales for a specific drink using the DrinkDetailComponent. However, upon initializing the component, only one backend call is being made to retrieve infor ...

Encounter an Unexpected Token Issue when using NextJS-auth0 in Jest

I am facing a problem with my Next.js app that is integrated with the nextjs-auth0 package. Whenever I attempt to test a particular file and include the following import: import { getSession } from '@auth0/nextjs-auth0'; An error occurs, stating ...

React Hook Form is flagging missing dependencies in the useEffect function

Before posting this question, I made an effort to search for a solution on Google. However, I am puzzled by the warning that the linter is giving me regarding my code. The warning message reads: ./components/blocks/Contact.tsx 119:6 Warning: React Hook us ...

Issue: The inject() function can only be executed within an injection context. Issue: An untruthy value was expected to be truth

I'm currently in the process of setting up a unit test for my app.component. I've imported all the necessary components, but I keep encountering an error that's puzzling me. I activated "preserveSymlinks": true in my angular.json file, but t ...

Having trouble compiling a Vue.js application with TypeScript project references?

I'm exploring the implementation of Typescript project references to develop a Vue application within a monorepo. The current structure of my projects is outlined below: client/ package.json tsconfig.json src/ ... server/ package.json t ...

Creating a data structure that filters out specific classes when returning an object

Consider the following scenario: class MyClass {} class MyOtherClass { something!: number; } type HasClasses = { foo: MyClass; bar: string; doo: MyClass; coo: {x: string;}; boo: MyOtherClass; }; type RemovedClasses = RemoveClassTypes& ...

Leveraging the Angular Material 2 table component to showcase data fetched from the backend system according to the user's present location

This question is similar to another one about how to get the current location in Typescript and pass it to a backend, which was answered by libertyernie. However, this time I need help with integrating the current location into an Angular Material 2 table ...

Tips for synchronizing the display of a table with the server response in an Angular application

* Project I am currently working on a project that involves retrieving player data from a json server and displaying it in a standard table format with a paginator. * Issue The challenge I'm facing is ensuring that the table data is loaded before th ...

It appears that using dedicated objects such as HttpParams or UrlSearchParams do not seem to work when dealing with Angular 5 and HTTP GET query parameters

I'm facing a perplexing issue that I just can’t seem to figure out. Below is the code snippet making a call to a REST endpoint: this.http.get<AllApplicationType[]>(environment.SUDS_API_SERVICE_URL + environment.SUDS_ALL_APPLICATIONS_URL, this ...

Do you think this is a clever way to circumvent using ENUM for a parameter?

As I continue to explore different coding styles in Typescript and Angular, I recently encountered a method without any comments attached to it. It seems like this method is enforcing that the value passed in must be one of the defined options, but strang ...

RXJS expand keeps on recursing indefinitely

After successfully uploading a file to Firebase, I implemented a recursive function to listen for GCP trigger logs. Everything seems to be working well, but I'm facing an issue where the recursive expand function never exits. Despite checking the val ...

Angular 8 does not show the default option in the select tag

When I use the following code snippet: <div style="text-align:center"> <form> <select type="checkbox" name="vehicle1" (change)="onchange()" > <option> 1 </option> <opti ...

What is the best way to retrieve class properties within an input change listener in Angular?

I am new to Angular and have a question regarding scopes. While I couldn't find an exact match for my question in previous queries, I will try to clarify it with the code snippet below: @Component({ selector: 'item-selector&apos ...

What is the process of converting an Array that is nested within an Object?

I am facing compile errors while attempting to convert an Object containing an Array of Objects. Here is the initial structure: export interface CourseRaw { metaInfo: MetaInfoRaw; gameCode: number; gameText: string; images?: ImageRaw[]; // Having ...

Having trouble locating the bootstrap import statement

Currently, I am working on a project in Angular where I have defined two styles in the angular.json file - styles.css and node_modules/bootstrap/dist/css/bootstrap.min.css. After running ng serve, it shows that it compiled successfully. However, upon ins ...

Ways to circumvent ng switch and create a component based on type

In my current code, I have an array called resourceTypes and I am using ngSwitch to create different components/directives based on the TypeName. However, I find this approach cumbersome as I have to update the code every time I add a new resource editor. ...

How can we effectively utilize LESS variables in styles.less when working with LESS files within components in Angular versions 6 or 7?

Running Angular version 7.0.0 will generate a folder structure typical for "ng new". Below is the content of my styles.less file: @personal-black: #0000; This snippet shows the content of my app.component.less file: ...