I am trying to filter an object's values. I assign a value to another object of the same type if the value is not undefined.
My code looks like this:
const unfiltered: {
name?: string;
age?: number;
} = {
name: 'Peter',
age: 20,
};
const filtered: typeof unfiltered = {};
let key: keyof typeof unfiltered;
for (key in unfiltered) {
if (unfiltered[key]) {
filtered[key] = unfiltered[key];
}
}
The problem, however, is that I get an error right at the assignment in the if clause that says:
Type 'string | number | undefined' is not assignable to type 'undefined'.
Type 'string' is not assignable to type 'undefined'. ts(2322)
I am pretty sure the errors stems from the fact that the properties inside the unfiltered object are optional and not all of the same type. So Typescript tries to match each occurring type in the unfiltered object with each occurring type in the filtered object which of of course will not result in the same type for the left and right hand side of an assignment. I tried to look for a solution on my own. In fact, I figured out two workarounds:
Deep-copy the unfiltered object. For every undefined value inside the resulting object, delete that value.
Create a type guard for each value of the unfiltered object and then assign the value to the filtered object by using the object access operator (.) instead of iterating through it by using the keys in combination with square brackets.
Although workaround 2 seems to be the go-to solution it can turn out to be quite a list of if-checks if an object has many keys. Is there a better way to achieve the filtering by using a type-safe and dynamic method? Am I doing something wrong in my sample code?