Skip to content

Instantly share code, notes, and snippets.

@disintegrator
Created May 1, 2018 22:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save disintegrator/bae0b97ce858d79d587a73451cfd015d to your computer and use it in GitHub Desktop.
Save disintegrator/bae0b97ce858d79d587a73451cfd015d to your computer and use it in GitHub Desktop.
PropType conditional type inference in TypeScript
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