Getting a subset of attributes from an object in Typescript: A step-by-step guide

For instance:

type T = {
  prop1: boolean;
  prop2: number;
  prop3: string;
};

const obj1 = {
  prop1: true,
  prop2: 1,
  prop3: 'hello',
  prop4: false,
  prop5: 'world'
}

const obj2: T = obj1 as T;  // the outcome is not as anticipated

Is there a way to dynamically assign obj2 to only include properties from obj1 that match type T?

In other words, retain matching properties and discard others. The desired result in this scenario would be equivalent to

const obj2: T = {
  prop1: obj1.prop1,
  prop2: obj1.prop2,
  prop3: obj1.prop3
}

This should happen dynamically considering that type T can change.

Answer №1

Unfortunately, TypeScript does not have a built-in feature that allows for this functionality. Implementing such a feature would involve utilizing reflection, which in turn would require TypeScript to generate a list of t's members in the JavaScript code it produces, something that is not typically done. Surprisingly, there is no mention of reflection in the official TypeScript documentation.

One possible workaround is to manually list the members of t in an array, despite the unavoidable duplication:

type t = {
  a1: boolean;
  a2: number;
  a3: string;
};
const t_members = ["a1", "a2", "a3"];

From there, you can then iterate through the properties using a simple loop:

const o2: t = {} as t;
for (const member of t_members) {
    o2[member] = o1[member];
}

To streamline this process if it's a common task, consider creating a utility function for it.

Answer №2

Upon closer inspection, it appears that Const o2 is morphing into a type-of object rather than just type t, thus inheriting all the properties being assigned to it.

Here's something you can try,

class t  {
  a1: boolean;
  a2: number;
    a3: string;
    constructor(a:any) {
        this.a1 = a.a1;
        this.a2 = a.a2;
        this.a3 = a.a3;
  }
};

type c={
     a1: boolean,
  a2: number,
  a3: string,
  a4: false,
  a5: string

}

const o1:c = {
  a1: true,
  a2: 1,
  a3: 'blah',
  a4: false,
  a5: 'blah blah'
}

let o2: t = new t(o1);

This approach may offer some assistance.

Answer №3

Try creating a custom function and testing it out:

var criteria = {
  a1: 'boolean',
  a2: 'number',
  a3: 'string'
};

const objectToClone = {
  a1: true,
  a2: 1,
  a3: 'hello!',
  a4: false,
  a5: 'another string'
}

function duplicate(obj, types) {
    if (null == obj || "object" != typeof obj) return obj;
    var copy = obj.constructor();
    for (var key in obj) {
    var val=obj[key];
    var exists=checkPresence(types,key,val);
    if(exists)
    {
     if (obj.hasOwnProperty(key)) copy[key] = obj[key];
    }
       
    }
    return copy;
}

function checkPresence(obj, oldKey, oldValue){
var response;
oldValue=typeof(oldValue);
for (var key in obj) {
    var val=obj[key];
        if(oldValue==val) // use (oldKey==key && oldValue==val) to verify all keys and values
        {
         response = true;
         break;
        }else{
         response = false;
        }
    }
    
    return response;
}

var result=duplicate(objectToClone,criteria);
console.log(result);

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 ECONNREFUSED error when making requests to an external API in a NextJS application integrated with Auth

Currently, I have integrated Auth0 authentication into my NextJS application by following their documentation. Now, I am in the process of calling an external ExpressJS application using the guidelines provided here: https://github.com/auth0/nextjs-auth0/b ...

The following middleware is not functioning properly on a local SSL server

When I run my Nextjs app without SSL using "next dev", the middleware functions as expected without any errors. However, if I attempt to run the app with SSL enabled, an empty middleware function triggers an error. The code for the middleware function (l ...

Searching for an object within an array in NodeJS that is not present in another array

One of my challenges involves working with two arrays of objects: var existingUsers1 = []; existingUsers1.push({ "userName": "A", "departmentId": "1" }); existingUsers1.push({ "userName": "B", "departmentId": "1 ...

Deleting outdated files in a temporary uploads directory - NodeJS best practices

My process for removing old files from a tmp upload directory involves the code below: fs.readdir( dirPath, function( err, files ) { if ( err ) return console.log( err ); if (files.length > 0) { files.forEach(function( file ) { ...

Display event using Angular

I am currently working on an Angular project where I need to print a specific area of the page. While I know that this can be done using media CSS, it is causing issues for me due to the numerous print functionalities present in the project. I am attemptin ...

Combining ng-repeat with manipulating the DOM beyond the scope of a directive

I'm struggling to understand Angular Directives and how they work. I have a simple array of objects in my controller, but creating the desired DOM structure from this data model is proving challenging. Any advice on best practices would be greatly app ...

Upon initial login, React fails to retrieve notes

I developed a note-taking React app using the MERN stack with React Router DOM v6. When I initially visit the website, I am directed to the login page as intended. However, upon logging in, the page refreshes but does not redirect to the home page. This is ...

Navigating on a page using anchor tags within a dropdown menu

I'm in the process of creating a top navigation bar with dropdown functionality that appears when hovering over certain navigation items. Here's how it currently looks: $(document).ready(function(){ $('[data-toggle="tooltip"]').t ...

Is there a way to use JavaScript to choose options within a <select> element without deselecting options that are disabled?

Here's the code snippet I am working with at the moment: <select id="idsite" name="sites-list" size="10" multiple style="width:100px;"> <option value="1" disabled>SITE</option> ...

Incorporate the module into both the parent and child class

In my coding project, I have a situation where both a parent class and a child class are importing the same lodash library. This raises the question: will the final bundled JavaScript file contain duplicate lodash code? //Parent Class import Component fro ...

Unable to display images using jquery

Just getting started. I'm attempting to load images from a folder. The HTML and JavaScript files are located in the same directory as the images, yet I am still unable to load them. $(function() { $('#main').append('<img src="plus. ...

The process of filtering arrays and utilizing the V-for directive in Vue.js

Utilizing Vue.js, I am attempting to iterate through an array of levels. I successfully received the response json in actions with a forEach function like: let filters = [] const array = response.data array.forEach((element) => ...

The error message "Vue.JS computed from VueX Store is not recognized" is displaying

Within my Vuex store, I am able to see it in the Vue Devtools tool. However, when attempting to load data into a computed property, an error message stating that it is not defined is displayed. computed: { userData(){ return this.$store.state.use ...

The power of absolute paths in React Native 0.72 with TypeScript

Hi everyone! I'm currently having some difficulty setting absolute paths in react native. I tried using babel-plugin-module-resolver, as well as configuring 'tsconfig.json' and 'babel.config.js' as shown below. Interestingly, VS Co ...

Filtering JSON array data in Typescript can help streamline and optimize data

Recently diving into Angular, I am facing a challenge with filtering data from a JSON array. My goal is to display names of items whose id is less than 100. The code snippet below, however, is not producing the desired result. list : any; getOptionList(){ ...

I want to show error messages using jquery only when the username or password is entered incorrectly. How can this be achieved?

document.getElementById("buttonClick").addEventListener("click", mouseOverClick); function mouseOverClick(){ document.getElementById("buttonClick").style.color = "blue"; } $("#buttonClick").hover(function() { $(this).css('cursor',&apos ...

Using AngularJS to refresh information stored in an array

My objective is to create a basic application that allows users to adjust their availability on weekdays. The code is functioning correctly as it retrieves data from the select box. However, I encounter an issue when trying to update Monday's data and ...

How can you identify the resume of a web application once you return from opening the camera?

I'm working on a web application that utilizes the camera by following steps from this solution: How to access a mobile phone's camera using a web app? However, I am trying to figure out how to implement a callback function once the user return ...

A step-by-step guide on implementing img source binding in Vue.js

<template> <div class="text-center"> <h1 class="display-4 my-5"><mark>GIGS</mark></h1> <b-container fluid="lg"> <b-row class="mx-auto"> <b-col lg="4" class=" ...

Execute Javascript after modification of the DOM

I have developed two custom directives known as app-content and app-content-item. These directives are intended to be utilized in upcoming projects to provide a basic structure with simple styling. They will be incorporated into a module and should be nest ...