Remove blank attributes from an object in TypeScript with type-safe
Removing blank attributes from an object is a common operation in JavaScript. Thanks to the new fromEntries syntax from ES10. We can now do this thing more simply with just one line:
However, in TypeScript, this is not a type-safe approach. For example, I defined an object with a null attribute:
TypeScript infers the type automatically as follows:
Unfortunately, after this object is processed by the above method:
TypeScript will only automatically determine the following types:
Obviously, this new object no longer retains its original attributes and type.
Such as id: number, title: string, createdDate: string, etc.
Therefore, we lose the attributes auto-completion provided by the IDE:
So, how to provide the correct type to the fromEntries method and keep all the attributes’ type-checking of TypeScript?
We can leverage the Index Signatures and Conditional Types syntax:
The following is the inferred result of using this custom type, Valuable:
You can find that TypeScript automatically inferred the non-null attributes and keep the types of all these non-null attributes. Not only ensures type safety, but also brings back the IDE’s autocomplete feature!
As a final step, rewrite the above into a helper function, getValuable, for easier reuse in the future
This helper function can be found in my GitHub Gist:
https://gist.github.com/miZyind/503c5330016f72c1a0517d3ec0903676
This function is the same the general JS method from StackOverflow, except that type safety is ensured in TypeScript: