Skip to content

Instantly share code, notes, and snippets.

@tatsushitoji
Last active December 27, 2018 23:27
Show Gist options
  • Save tatsushitoji/92c2d061ec69f4c77954f40231ed3a78 to your computer and use it in GitHub Desktop.
Save tatsushitoji/92c2d061ec69f4c77954f40231ed3a78 to your computer and use it in GitHub Desktop.
static getDerivedStateFromProps HOCs with TypeScript
type DerivedStateFromPropsFunction<TProps, TState> = (
props: TProps,
state: TState,
) => TState | void;
const getDerivedStateFromProps = <T extends {}>(
f: DerivedStateFromPropsFunction<T, T | {}>,
) => (BaseComponent: React.ComponentType<T>) => {
class EnhancedComponent extends React.Component<T> {
state = {};
static getDerivedStateFromProps(nextProps: T, prevState: T | {}) {
return f(nextProps, prevState) || null;
}
render() {
return React.createFactory(BaseComponent as React.ComponentClass<T>)({
...this.props,
...this.state,
});
}
}
return EnhancedComponent;
};
@tatsushitoji
Copy link
Author

Line:16 any casting is no longer needed.
ref: https://github.com/Microsoft/TypeScript/wiki/What's-new-in-TypeScript

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment