Remap Objects Function with Correct Return Data Type

After receiving data from another source via a post request in a large object, I need to extract specific fields and organize them into more precise objects with some fields remapped before inserting them into a database.

Currently, I have a working solution that's not generic. However, I aim to create a more generic function while maintaining complete type safety.

This code snippet is a simplified version of where I stand right now.

import type { O } from 'ts-toolbelt';

const userFields = {
  accountFirstName: 'firstName',
  accountLastName: 'lastName',
  email: 'email',
  cellphone: 'cellPhone',
  city: 'city',
  state: 'state',
  street: 'street',
  zip: 'zip',
} as const;


const playerFields = {
  playerId: 'sc_id',
  playerFirstName: 'firstName',
  playerLastName: 'lastName',
  sizingJersey: 'jerseySize',
  sizingShorts: 'shortSize',
} as const;

const allFields = {
    ...userFields,
    ...playerFields
}

type EventData = typeof allFields;
type InvertedRecord<R extends { [P in keyof R]: R[P]; }> = Record<keyof O.Invert<R>, string>;

type UserRecord = InvertedRecord<typeof userFields>

function objectKeys<Obj> (obj: Obj): (keyof Obj)[] {
  return Object.keys(obj) as (keyof Obj)[];
};

// take just the user fields from the full data object and put them into a new object 
const extractUser = (data: EventData) => {
  const user: Partial<UserRecord> = {};
  objectKeys(userFields).forEach((field) => {
    user[allFields[field]] = data[field];
  });
  return user as UserRecord;
};

// A more generic extract function that takes the list of fields and the data object and extracts the fields into a new object
function genericExtract <T>(fields: T, data: EventData): T {
  const obj: Partial<T> = {};
  objectKeys(userFields).forEach((field) => {
    obj[allFields[field]] = data[field]; // <--- obj's type doesn't get properly inferred so the assignment is not compatible
  });
  return obj as T;
}

TS Playground link for more context on the issue hat hand..

Second Playground link

Answer №1

To begin with, a straightforward method to extract the values of an object type:

type Values<T> = T[keyof T];

The concern here is that T in function genericExtract lacks constraints. This leads to allFields[field] not necessarily being a key of T, resulting in an error.

An effective solution is to impose a constraint on T:

function genericExtract <T extends Record<Values<typeof allFields>, unknown>>(fields: T, data: EventData): T {

Try it out

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

Leveraging and utilizing TypeScript npm packages

My goal is to create shared code in TypeScript, package it as an npm package, and easily install it. I attempted to create an external library like this: export class Lib { constructor(){ } getData(){ console.log('getting data from l ...

Transferring HTML variables to an Angular Component

I am currently trying to transfer the information inputted into a text-box field on my webpage to variables within the component file. These variables will then be utilized in the service file, which includes a function connected to the POST request I exec ...

Leveraging a React hook within a Next.js API route

I am looking for a way to expose the data fetched by a React.js hook as a REST endpoint using Next.js. To create a REST endpoint in Next.js, I can easily use the code below in pages/api/index.tsx export default function handler(req: NextApiRequest, res: N ...

Error: Local variable remains undefined following an HTTP request

Whenever I make http calls, my goal is to store the received JSON data in a local variable within my component and then showcase it in the view. Service: getCases(){ return this.http.get('someUrl') .map((res: Response) => res.jso ...

What is the best way to choose a key from a discriminated union type?

I have a discriminated union with different types type MyDUnion = { type: "anonymous"; name: string } | { type: "google"; idToken: string }; I am trying to directly access the 'name' key from the discriminator union, like thi ...

The function `find()` will not provide any data, it will only output `undefined`

I am trying to extract the `s_id` field from this JSON data: { "StatusCode": 0, "StatusMessage": "OK", "StatusDescription": [ { "s_id": "11E8C70C8A5D78888E6EFA163EBBBC1D", "s_serial": " ...

What is the proper way to define the type when passing a function as a component prop, with or without parameters?

import { dehydrate, HydrationBoundary } from '@tanstack/react-query'; import getQueryClient from '@/lib/react-query/getQueryClient'; export async function RQBoundary<T>({ children, queryKey, fn, }: { children: React.Reac ...

TypeScript Tutorial: How to retrieve the data type of a deeply nested object

I have a question about extracting the type of a nested object with similar structures. The object in question contains multiple sub-objects that all follow the same pattern. const VALUES = { currentStreak: { display: "Current streak", ...

Encountered a runtime error in NgRx 7.4.0: "Uncaught TypeError: ctor is not a

I'm facing difficulties trying to figure out why I can't register my effects with NgRx version 7.4.0. Despite simplifying my effects class in search of a solution, I keep encountering the following error: main.79a79285b0ad5f8b4e8a.js:33529 Uncau ...

Is it more beneficial to convert all the current jQuery AJAX webparts into Typescript or should I opt to inject the existing jQuery into SPFX instead?

Transitioning from SharePoint 2013 to SharePoint online raises the question of how to migrate existing webparts that utilize jquery - ajax to SPFX client webparts. One possibility is rewriting all the code in Typescript, but is it possible to simply inje ...

Tips on transforming Angular 2/4 Reactive Forms custom validation Promise code into Observable design?

After a delay of 1500ms, this snippet for custom validation in reactive forms adds emailIsTaken: true to the errors object of the emailAddress formControl when the user inputs [email protected]. https://i.stack.imgur.com/4oZ6w.png takenEmailAddress( ...

A keyboard is pressing on tabs and navigating through the app's contents in Ionic 3 on an Android device

I'm currently working on an IONIC 3 app and facing a challenge. When I tap on the ion search and the Keyboard pops up in ANDROID, it disrupts the layout by pushing all the content around. Original screen: Keyboard mode active: Things I've tri ...

Typescript feature: Configuring BaseUrl with nested directories

When utilizing the 'baseUrl' property along with the 'paths' property in this manner: "baseUrl": "./src", "paths": { "app-component": [ "app/app.component"], "test-component": [ "app/test/test.component" ] } the compilation proces ...

The identifier 'name' is not found in the specified data type

How can I resolve the error 'Property 'name' does not exist on type' in TypeScript? Here is the code block : **Environment.prod.ts** export const environment = { production: true, name:"(Production)", apiUrl: 'https://tes ...

How can I update a dropdown menu depending on the selection made in another dropdown using Angular

I am trying to dynamically change the options in one dropdown based on the selection made in another dropdown. ts.file Countries: Array<any> = [ { name: '1st of the month', states: [ {name: '16th of the month&apos ...

Typescript's default string types offer a versatile approach to defining string values

Here is an example code snippet to consider: type PredefinedStrings = 'test' | 'otherTest'; interface MyObject { type: string | PredefinedStrings; } The interface MyObject has a single property called type, which can be one of the ...

What is the best way to link function calls together dynamically using RXJS?

I am seeking a way to store the result of an initial request and then retrieve that stored value for subsequent requests. Currently, I am utilizing promises and chaining them to achieve this functionality. While my current solution works fine, I am interes ...

I am developing a JWT authentication and authorization service for my Angular application. However, I am running into issues when trying to implement observables

I have created a user class and required interfaces as outlined below: user.ts import { Role } from '../auth/auth.enum' export interface IUser { _id: string email: string name: IName picture: string role: Role | string userStatus: b ...

Using TypeScript to asynchronously combine multiple Promises with the await keyword

In my code, I have a variable that combines multiple promises using async/await and concatenates them into a single object const traversals = (await traverseSchemas({filename:"my-validation-schema.json"}).concat([ _.zipObject( [&quo ...

Utilizing interpolation in Angular to apply CSS styling to specific sections of a TypeScript variable

Suppose I have a variable called data in the app.component.ts file of type :string. In the app.component.html file, I am displaying the value of data on the UI using string interpolation like {{data}}. My question is, how can I apply some css to specific ...