Skip to content

Instantly share code, notes, and snippets.

@zaverden
Created June 1, 2020 12:42
Show Gist options
  • Select an option

  • Save zaverden/96c77a53d795d2890141dcf12919e651 to your computer and use it in GitHub Desktop.

Select an option

Save zaverden/96c77a53d795d2890141dcf12919e651 to your computer and use it in GitHub Desktop.
withOptional
type NullPartial<T> = {
[P in keyof T]?: T[P] | null;
};
type Optional<T, K extends keyof T> = Omit<T, K> & NullPartial<T>;
function withOptional<TProps, TOpts extends Array<keyof TProps>>(
Wrapped: ComponentType<TProps>,
optionals: TOpts,
Placeholder: ComponentType<Optional<TProps, TOpts[number]>>,
): ComponentType<Optional<TProps, TOpts[number]>> {
return props => {
if (optionals.some(f => props[f] == null)) {
return <Placeholder {...props} />;
}
return <Wrapped {...(props as TProps)} />;
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment