Last active
December 27, 2018 23:27
-
-
Save tatsushitoji/92c2d061ec69f4c77954f40231ed3a78 to your computer and use it in GitHub Desktop.
static getDerivedStateFromProps HOCs with TypeScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Line:16
any
casting is no longer needed.ref: https://github.com/Microsoft/TypeScript/wiki/What's-new-in-TypeScript