Skip to content

Instantly share code, notes, and snippets.

@amalu-sajeev-me
Last active November 26, 2022 10:01
Show Gist options
  • Save amalu-sajeev-me/ef5d4551b68e470e7ffea66abe22feef to your computer and use it in GitHub Desktop.
Save amalu-sajeev-me/ef5d4551b68e470e7ffea66abe22feef to your computer and use it in GitHub Desktop.
Utility methods in Typescript
export const isPropAvailable = <T extends object>(
inputObject: T,
prop: string
): null | T[keyof T] => {
if (typeof inputObject !== "object") return null;
if (prop in inputObject) return inputObject[prop];
return null;
};
export const deepNullCheck = <T extends object>(
inputObject: T,
propsToCheck: string[] | string
) => {
if (typeof propsToCheck === "string")
return isPropAvailable(inputObject, propsToCheck);
return propsToCheck.reduce((prev: object, accu) => {
return isPropAvailable(prev, accu);
}, inputObject);
};
export const omitProps = <T extends object>(obj: T, arr: (keyof T)[]) =>
Object.keys(obj).reduce(
(prev, curr) =>
arr.includes(curr as keyof T) ? prev : { ...prev, [curr]: obj[curr] },
{}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment