Ensure my function returns mutated object as instanceof the same class typescript? Ensure my function returns mutated object as instanceof the same class typescript? typescript typescript

Ensure my function returns mutated object as instanceof the same class typescript?


This solution will mutate the input object by removing the 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 seems it works for your test case: Test in typescript playground


Yes, with each iteration of reduce you are returning a new {} which is an instance Object.

So to make the return object of same instace as of argument you should make following changes.

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);};

or you can use new obj.__proto__.constructor as per the target of typescript output you are using.

Reply in case you have typescript issues with this code snippet.