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.