Last active
August 24, 2024 06:50
-
-
Save miZyind/503c5330016f72c1a0517d3ec0903676 to your computer and use it in GitHub Desktop.
A helper function to remove blank attributes from an object in TypeScript with type-safe
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type Valuable<T> = { [K in keyof T as T[K] extends null | undefined ? never : K]: T[K] }; | |
function getValuable< | |
// eslint-disable-next-line @typescript-eslint/ban-types | |
T extends {}, | |
V = Valuable<T>, | |
>(obj: T): V { | |
return Object.fromEntries( | |
Object.entries(obj).filter( | |
([, v]) => | |
!( | |
(typeof v === 'string' && !v.length) || | |
v === null || | |
typeof v === 'undefined' | |
), | |
), | |
) as V; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment