How can I make sure that my function returns a mutated object that is an instance of the same class in

export const FilterUndefined = <T extends object>(obj: T): T => {
  return Object.entries(obj).reduce((acc, [key, value]) => {
    return value ? { ...acc, [key]: value } : acc;
  }, {}) as T;
};

During a database migration process, I encountered a situation where some values for certain keys were specifically set to undefined. Even though the key still existed, the value was undefined.

To address this issue, I created a function, but I noticed that after applying this function to modify a class object, the resulting object was no longer an instance of the same class. How can I ensure that the returned object is of the same class as the input parameter?

The use of as T seemed to silence the TypeScript compiler but did not fully resolve the issue.

I attempted to obtain the prototype of the object and then use return new prototype(obj) or

return new prototype.constructor(obj)
, but this did not yield the desired outcome.

Upon console logging the prototype, it displayed as follows:

PROTOTYPE TestClass {}

I conducted a test with the following setup:

  it('should return the same type that it receives', () => {
    class TestClass {
      name: string;
      optionalProperty?: any;
    }

    let testObject = new TestClass();
    testObject.name = 'My Name';
    testObject.optionalProperty = undefined;

    console.log(testObject instanceof TestClass);
    testObject = FilterUndefined(testObject);

    console.log(testObject instanceof TestClass);
    console.log(testObject);

    expect(testObject).instanceOf(TestClass);
  });

Furthermore, here is a link to a JSFiddle for testing: https://jsfiddle.net/3sdg98xt/2/. When copy-pasted from VSCode, an error 'expected expression, got ';'' was encountered despite functioning properly.

Answer №1

This code snippet modifies the original object by eliminating any keys with undefined values.

function removeUndefined <T>(object: T): T {
    for (const id in object) {
       if (object[id] === undefined) {
          delete object[id];
       }
    }
    return object;
}

It appears to be effective for the given test case: Test in typescript playground

Answer №2

Absolutely, during each iteration of the reduce function, a fresh {} is generated, constituting an instance of the Object class.

To ensure that the returned object is of the same instance as the argument, you need to implement the following modifications.

export const FilterUndefined = (obj) => {
return Object.entries(obj).reduce((acc, [key, value]) => {
    if (value) {acc[key] = value;}
    else {delete acc[key]}
    return  acc;
  }, new obj.constructor);
};

Alternatively, you have the option to utilize new obj.__proto__.constructor depending on the specified target in your typescript configuration.

If you encounter any typescript-related challenges with this code snippet, feel free to reach out for further assistance.

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

Tips for correctly linking JS and CSS resources in Node.js/Express

I have a JavaScript file and a stylesheet that I am trying to link in order to use a cipher website that I created. Here is my File Path: website/ (contains app.js/html files and package json) website/public/css (contains CSS files) website/public/scri ...

Issue with MongoDB find() function not retrieving any results (Assignment)

I am currently working on an assignment that requires the use of noSQL databases. Although I understand most of the queries we have to perform in mongoDb, every query I execute seems to return a blank result. Initially, we are required to create a collect ...

Updating the component following an API request in ReactJS

I'm currently working on a component that allows users to search for friends by entering their email address. The interface consists of an input form where users can submit the email and I want to display the friend's information below the form a ...

When working with THREE.js in Electron, web development tools seem to vanish into thin air

Exploring electron is fairly new to me (if you know of any good documentation, please leave it in the comments) and I've encountered an issue that has left me puzzled: Everything seems fine until I load the THREE.js library. At that point, even thoug ...

Experimenting with a sample post on a minimalist Node.js application using Mocha and Superagent

I trust you are having a splendid day. Currently, I am focusing on enhancing my TDD skills in Node.js. To practice, I have developed a minimalistic application that handles basic GET and POST requests. The app simply displays a straightforward form to the ...

Exploring the use of barcodes with node.js

Having some issues with generating a barcode using a barcode module from NPMJS called npm i barcode. I am getting an error message res is not defined even after following the instructions. Can someone please guide me in the right direction? Here is my code ...

Can a layer be sliced to create a text-shaped cutout?

I want to achieve a cool text effect where the background is visible through the letters. I have explored options with background images and colors, but I haven't found any examples where the underlying layer is revealed. Is this even possible? Imag ...

A new marker has been created on the Ajax Google Map, however, the old marker is still displaying as

Hey, I'm currently working on retrieving marker latitudes and longitudes using Ajax. I am receiving Ajax data every second and successfully creating markers within a specific radius. However, I'm running into an issue with updating marker positio ...

Is there a way to prevent Backbone.js from deleting surrounding elements with 'default' values?

Trying to articulate this question is a challenge, so please let me know if further clarification is needed. As I am new to backbone.js, my inquiry may seem basic. My goal is to utilize backbone to efficiently generate graphs using the highcharts library. ...

Craft a function within the recompose library

As I was exploring the compose function in recompose library by @acdlite to combine boundary conditions for Higher Order Components, I came across two different implementations of the compose function: const compose = (...funcs) => funcs.reduce((a, b) ...

Determine whether an element is visible following a state update using React Testing Library in a Next.js application

I'm looking to test a NextJS component of mine, specifically a searchbar that includes a div which should only display if the "search" state is not empty. const SearchBar = () => { const [search, setSearch] = useState(""); const handleSear ...

Get the download URL from Firebase Storage and save it into an array within Firestore

I am currently working on a project to upload multiple image files to Firebase Storage and then store their download URLs in a single array within Firestore. uploadImages(name, images) { for (let i = 0; i < images.length; i++) { const file = ...

What is the best way to utilize a basic jQuery hide/show function to display everything before hiding it?

I have a dropdown menu where selecting an option will display a specific section based on the matching value and class, while hiding all other sections. How can I set it up so that before any selection is made, all sections are displayed and only hide afte ...

Remove duplicate JSON records in JavaScript by comparing and filtering based on identical attributes

Looking to remove duplicates from a JSON object [{id:1,name:a, cat:1},{id:1, name:a, cat:2},{id:2, name:b, cat:8}] I want to keep only the first occurrence of each duplicated id [{id:1,name:a, cat:1},{id:2, name:b, cat:8}] ...

Unable to retrieve obj after using $location.url

I am working with two different views. In the first view, I call a function from the admin controller using AngularJS: <a ng-click="updateAdmin(admin)">update</a> The code in the admin controller looks like this: $scope.updateAdmin = functio ...

After triggering an action, I am eager to make a selection from the store

To accomplish my task, I must first select from the store and verify if there is no data available. If no data is found, I need to dispatch an action and then re-select from the store once again. Here is the code snippet that I am currently using: t ...

When should you use isRequired for PropType versus defaultProps in a React application?

I often find myself confused about when to use .isRequired versus .defaultProps={...}. I personally feel that I should avoid using isRequired, as it seems like creating a potential bug in the application. By using isRequired, it automatically removes the n ...

The issue lies within typescript due to process.env.PORT being undefined

I am a newcomer to working with TypeScript. Even after importing and using the dotenv package, I am still encountering issues with getting undefined values. Do I need to declare an interface for the dotenv variables? import express,{Application} from &apo ...

Ways to efficiently implement configuration settings in a functional approach

I've delved into the world of functional programming and I'm working on developing a package that needs to be configurable. My goal is to set up this configuration only once to maintain purity in my functions without relying on global state. Curr ...

Tips for validating a form's input on an ajax page with the help of jQuery

I am facing an issue with a form containing two inputs. The first input can be validated before triggering an ajax function, but the second input cannot be validated. The second input is loaded from a page using ajax, along with the submit button. I need t ...