Created
May 1, 2018 22:46
-
-
Save disintegrator/bae0b97ce858d79d587a73451cfd015d to your computer and use it in GitHub Desktop.
PropType conditional type inference in 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
import { ComponentType } from "react"; | |
/** | |
* For any type T that is a React.ComponentType give me the type of its Props | |
* | |
*/ | |
export type PropType<T> = T extends ComponentType<infer P> ? P : never; | |
// USAGE: | |
import { Component, Fragment } from "react"; | |
type ButtonProps = { | |
color: "blue" | "green"; | |
}; | |
// This can be some button in a third party library or one you want to | |
// gradually remove from your codebase | |
const Button: React.SFC<ButtonProps> = () => <button />; | |
// Your newer button component can leech its prop type and add its own on top | |
type NewerButtonProps = PropType<typeof Button> & { | |
size: "small" | "large"; | |
}; | |
class NewerButton extends Component<NewerButtonProps> {} | |
const Example = () => ( | |
<Fragment> | |
<Button color="blue" /> | |
<NewerButton color="green" size="large" /> | |
</Fragment> | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment