Exploring ways to maintain the type integrity of a mapped object within Typescript

Suppose I have a dictionary object like this:

const x = {
  foo: {inner: 3},
  bar: {inner: 'hi'},
};

The inner property has different types (in this case, string and number).

My goal is to transform it into a structure that appears as follows:

const y = {
  foo: 3,
  bar: 'hi',
};

However, I want to achieve this transformation automatically while preserving the type information. Can this be done in Typescript?

I've made some progress using lodash:

import { mapValues } from 'lodash';
const y: Y = mapValues(x, (z) => z.inner);

But this results in a union of all types in the dictionary:

const y: {
    foo: string | number;
    bar: string | number;
}

Instead of what I actually want:

const y: {
  foo: number;
  bar: string;
};

Answer №1

Here's a possible solution that could do the trick:

type Nested<T> = {[K in keyof T]: {nested: T[K]}};

function unnest<T>(data: Nested<T>): T {
  // This is just a placeholder implementation
  return _.mapValues(data as any, item => item.nested) as T;
}

const unwrappedData = unnest(inputData);

Check out this resource for more information: https://www.typescriptlang.org/docs/handbook/advanced-types.html (the final paragraph)

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

Turn off the ability to select months in PrimeNG Calendar using Typescript

In my Angular 7 project, I am utilizing PrimeNG Calendar and I am looking to disable the month navigator at the component level based on certain conditions. For example, if the current month is February, I want to disable the month navigator after March. ...

There seems to be an issue with Angular 8's *ngIf not correctly updating the UI in the navigation bar

I am currently working on integrating bootstrap@4 with an Angular 8 application to ensure full responsiveness. In the navigation bar, certain elements such as the logout button or link should be hidden if the user is not registered or logged in, and vice ...

Unable to access specific route in Angular if default route contains a parameter

Here is a list of my routes: const routes: Routes = [ { path: '', component: BlogLayoutComponent, children: [ { path: ':pageNumber', component: HomeComponent }, { path: '&apo ...

Do not directly change a prop's value as it will be replaced when the parent component re-renders. Use v-form instead

I'm currently in the process of developing an app using nuxt along with vuetify 2.x, and I keep encountering a specific error message: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Inste ...

Ensure all promises are resolved inside of for loops before moving on to the next

Within my angular 11 component, I have a process that iterates through elements on a page and converts them from HTML to canvas to images, which are then appended to a form. The problem I am encountering is that the promise always resolves after the ' ...

Ways to specify an array type with unique elements that all have the same generic type as the rest?

Recently I've been dedicated to enhancing my open-source library, but I've run into a puzzling issue that has me stumped. Let's take a look at the code snippet: In my setup, I have an array containing functions designed for transformations ...

Loop through an enum in ion-select

How can I use ngModel to iterate through an enum with ion-select? export enum EducationLevel { ILLITERATE = "Illiterate", 1_TO_3_YEARS = "1 to 3 years", 4_TO_7_YEARS = "4 to 7 years", MORE_THAN_8_YEARS = "more than 8 years" } class Person ...

Is it Mission Impossible to Combine NodeJs, Restify, SQL Server, TypeScript, and IIS?

Starting a Rest API project using NodeJS with Restify on a Windows environment (local server with IIS and SQLServer) while also using Typescript may seem like a difficult task. Is it an impossible mission? Does anyone have any helpful guides, documentatio ...

Ways to pass styling properties to a nested component

I am working on a component that includes an input field: <mat-form-field appearance="standard"> <mat-label >{{label}}<span>*</span></mat-label> <input [type]="type" <span matSuffix>{{suffix} ...

Tips for implementing Root Import in React Testing Library for React applications

Whenever I bring my components or pages into my testing file ".spec.tsx", it doesn't seem to recognize Babel Root Import. https://i.sstatic.net/exuKl.png Is there a way to configure my ".spec.tsx" file to acknowledge "~" as the Root Import? The Fou ...

`The flaw in filtering logic - an analysis`

Looking to find matching records within two Lists. We have a List called allAnimals with attributes like animalId, and another List named domesticAnimals also containing animalId. The goal is to compare the two lists and create a new list where the anima ...

Encountering a syntax error when attempting to utilize the colon symbol for specifying data types

Currently, I am a novice who is delving into the world of TypeScript. Here is a snippet of code that I have written: let num: number = 123; console.log(123); However, when attempting to run this file using Node.js and saving it as test.ts, I encounter the ...

Having trouble logging in with Google using React, Redux, and Typescript - encountered an error when attempting to sign in

As a beginner in TS, Redux, and React, I am attempting to incorporate Google Auth into my project. The code seems functional, but upon trying to login, an error appears in the console stating "Login failed." What adjustments should be made to resolve thi ...

The Typescript code manages to compile despite the potential issue with the type

In my coding example, I have created a Try type to represent results. The Failure type encompasses all possible failures, with 'Incorrect' not being one of them. Despite this, I have included Incorrect as a potential Failure. type Attempt<T, ...

The axios GET request failed to return a defined value

My current issue involves making a get request using the following code snippet: router.get('/marketUpdates',((request, response) => { console.log("market updates"); var data: Order[] axios.get('http://localhost:8082/marketUpdates& ...

Issue with Vue plugin syntax causing component not to load

I'm facing an issue with a Vue plugin that I have. The code for the plugin is as follows: import _Vue from "vue"; import particles from "./Particles.vue"; const VueParticles = (Vue: typeof _Vue, options: unknown) => { _Vue. ...

Having trouble retrieving values from the getEntry method in Contentful

How can I retrieve an entry from contentful using Contentful v10 with Node.js 18? I am having trouble accessing the value in getEntry(). interface Example { contentTypeId: 'item' fields:{ title: EntryFeildTypes.Text rate: EntryFeildType ...

The Assertion of Field Values in Typescript

I'm currently utilizing https://github.com/stephenh/ts-proto to create TypeScript types from protobuf messages by using type unions for handling `oneOf` fields. An example of a type is as follows: export interface Milestone { milestoneLabel?: ...

Encountering an issue with managing promises in Observables for Angular HTTP Interceptor

Currently, I am encountering the following situation: I have developed an authentication service using Angular/Fire with Firebase authentication. The authentication service is expected to return the ID token through the idToken observable from Angular/Fir ...

Using Arrow Functions in Angular 2 Typescript with Support for IE11

Are arrow functions in Typescript for Angular2 compatible with IE 11? I have come across information stating that arrow functions in javascript may not be supported in IE 11, but I am uncertain if the same applies to Typescript. ...