Skip to content

Instantly share code, notes, and snippets.

@miZyind
Last active April 12, 2024 14:56
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save miZyind/503c5330016f72c1a0517d3ec0903676 to your computer and use it in GitHub Desktop.
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
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