Generate or acquire basic data types based on function behavior using TypeScript

Imagine you have an object like this:

const exampleObject = {
   key1: {id: 1},
   key2: {id: 1},
   key3: {id: 1},
   key4: {id: 1},
   ....
}

and a function that transforms the object to:

const transformedObject = {
   key1: 1,
   key2: 1,
   key3: 1,
   key4: 1,
   ....
}

using a function like this:

function transformObject<MyInputInterface>(input: MyInputInterface): MyOutputInterface? {
  const newObject = {};
  _.forIn(input, (value, key) => {
      newObject[key] = value.id;
  }
  return newObject;
}

Is there a method in Typescript where you can define just one interface that automatically captures the structure of the other interface (either input or output)? For instance, passing MyInputInterface into the function will yield MyOutputInterface?

This kind of scenario frequently arises in my codebase where a library extracts metadata and only provides specific values (e.g. id). I could create separate interfaces for input/output to gain more type information, but I'm curious to know if there's a way to define either input OR output and derive the other type information implicitly.

To illustrate this concept better, consider the following example:

const data = {
   propA: {
      desc: 'property a',
      val: 1
   },
   propB: {
      desc: 'property b',
      val: 'hello'
   }
   // any number of properties
};

needs to be converted to:

const processedData = {
  propA: 1,
  probB: 'hello'
};

Answer №1

Here is a sample code snippet to achieve this:

const myObject = {
    propA: {
        desc: 'property a',
        val: 1
    },
    propB: {
        desc: 'property b',
        val: 'hello'
    }
};

function convertObject(obj, propName) {
    let newObject = {};
    for(let key in obj){
        newObject[key] = obj[key][propName];
    }
    return newObject;
}

console.log('newObject', convertObject(myObject, 'val'));

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

I'm trying to figure out how to incorporate this code into an arrow function while also utilizing the iterating array element

I am aiming to create a function that can provide either true or false based on whether the searchElement exists in the array. While I could achieve this with a simple for loop and if-else statement, my goal is to utilize an arrow function. Although JavaS ...

Combining arrays within an array with the help of lodash

What is the best way to combine arrays within an array using lodash? Consider this scenario: Input: var x = [ [1,2,3,4], [5,6,7], [], [8,9], [] ]; Desired output: x = [1,2,3,4,5,6,7,8,9]; Presently, my code performs the following function: return pr ...

Problem encountered when trying to use a single button for both opening and closing functionality in JQuery

Hello everyone, I'm currently working on creating a button that toggles between opening and closing. When clicked the first time, it should open, and when clicked the second time, it should close and reset. Here is the code I've written so far. ...

Step-by-step guide to swapping an element with a textarea element using javascript

My current project involves creating a user profile that includes a text box where users can describe themselves. I've already implemented a separate page for editing the profile, but now I want to add a feature where users can hover over their descri ...

Placing pins on Google Maps

I'm attempting to display two separate markers on two individual maps positioned next to each other on my website. <script type="text/javascript"> var map, map2; function initialize(condition) { // setting up the maps var myOptions = { zoo ...

Determine time without discerning the timezone of the device

This script checks the current time against a specified deadline time. // Get current date/time var now = new Date(); // Set up deadline date/time var deadline = new Date(); //deadline is 1830hrs; deadline.setHours(18); deadline.setMinutes(30); // Chec ...

Is it possible to expand the CORS permissions to the routers directly from the app?

I have a couple of questions: Is it possible to just use cors() once in my server.js instead of having to call and use it in every router file? Can I simply require express once in my server.js without having to call it in all my router files? Currently, ...

The focus functionality in Angular seems to be malfunctioning

Having trouble with simple focus in Angular <div class="search pull-right tab-{{ showDetails2 }}" data-ng-click="showDetails2 = !showDetails2; showDetails = false; showDetails1 = false;searchFocus();"> html <input type="text" data-ng-model="mod ...

Unable to expand the width of the video element

So I have encountered a situation like this The video displayed does not fully expand to the width of its containing element. This is what my HTML structure looks like - <div class="webcam"/> <div class="control-container"> </div> ...

When I integrate the Google map on my website, it appears to be fully zoomed out by default. However, if you access the map directly through the link provided, it

After creating a custom public map on google.maps, I noticed that the embedded version on my site is zoomed out too far and not centered on my location like the original. You can view it here. Here's the code I'm using to embed the map: <ifr ...

Spin CSS card with a button press

Is there a way to rotate a CSS card only by clicking on a specific button? Currently, the card rotates when clicked anywhere on it. How can I make it so that it changes rotation only on a button click? I tried modifying the JavaScript code from ('. ...

Converting values to hexadecimal in PHP inspired by Javascript's .toString(16)

Is there a way to achieve the same result as JavaScript's .toString(16) in PHP? var n = 200000002713419; console.log(n.toString(16)); When executed, this code returns b5e6211de74b. Is there any equivalent function in PHP to achieve the same output? ...

Field for user input along with a pair of interactive buttons

I created a form with one input field and two buttons - one for checking in and the other for checking out using a code. However, when I submit the form, it leads to a blank page in the php file. What could be causing this issue? UPDATE After changing fro ...

Trouble accessing index upon clicking paginated outcomes in Angular

I'm encountering a problem with my app. I have paginated results, but when I use the variable let i = index in ngFor, it only retrieves results for the first 10 items and not the paginated ones. For example, if I go to page 2 and click on the first it ...

Wondering how to implement HubSpot Conversations SDK in a Typescript/Angular application?

Recently, I came across some useful javascript code on this website window.HubSpotConversations.widget.load(); window.HubSpotConversations.widget.refresh(); window.HubSpotConversations.widget.open(); window.HubSpotConversations.widget.close(); Now, I am l ...

Eliminate event listener using unique identifier

Is there a way to retrieve information about all event handlers for an element in JavaScript? $._data($('#element_id')[0], "events"); This will provide a detailed record of every event handler attached to the element. 0: {type: "c ...

Checking phone numbers in JavaScript utilizing regular expressions while retaining the same keypress functionality

Using regular expression in JavaScript, validate a phone number with functionality similar to keypress. $('#phone').keypress(function(e) { var numbers = []; var keyPressed = e.which; for (var i = ...

The Angular routing functionality appears to be malfunctioning

I am currently implementing routing in my project using basic angular route with Angular 1.3.0. Here is the content of my app.js file: 'use strict'; var routerApp = angular.module('mcw', [ 'ngRoute', 'mcw.controll ...

Steps to integrate Framework7 with Ionic 2

Is there a way to incorporate framework7 into a ionic2 project? I have successfully installed framework7 in my ionic2 project using the following command: npm i framework7 --save My next step is to add the typescript definition to the project by downloa ...

deployJava.js injects a new <embed> element into the header section of the webpage

I've ran into an issue with the Java applets on my website. I included the deployJava.js load tag in the head section of the page, but when I look at the resulting HTML in Chrome debugger, this script seems to be breaking my head content and starting ...