Skip to content

Instantly share code, notes, and snippets.

@tomasfrancisco
Last active February 28, 2019 12:37
Show Gist options
  • Save tomasfrancisco/17bae55af2f6d89800ea8a837d3dc787 to your computer and use it in GitHub Desktop.
Save tomasfrancisco/17bae55af2f6d89800ea8a837d3dc787 to your computer and use it in GitHub Desktop.
React type safe Higher-Order Component (HOC)
import * as React from "react";
export interface DecoratedProps {
prop1: string;
prop2: number;
}
export interface DecoratedOptions {
option1: string;
option2: number;
}
export function withDecoratedProps<OwnProps extends DecoratedProps>(
options: DecoratedOptions
) {
type Omit<T, K> = Pick<T, Exclude<keyof T, K>>;
type Subtract<T, K> = Omit<T, keyof K>;
type FilteredProps = Subtract<OwnProps, DecoratedProps>;
return function(
Component: React.ComponentType<OwnProps>
): React.ComponentType<FilteredProps> {
return class Decorator extends React.Component<FilteredProps> {
public render() {
return (
<Component {...this.props as OwnProps} prop1={"prop1"} prop2={2} />
);
}
};
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment