Skip to content

Instantly share code, notes, and snippets.

@brieb
Created February 7, 2019 09:59
Show Gist options
  • Star 89 You must be signed in to star a gist
  • Fork 17 You must be signed in to fork a gist
  • Save brieb/48698aca8565310db4453b9ff875dee3 to your computer and use it in GitHub Desktop.
Save brieb/48698aca8565310db4453b9ff875dee3 to your computer and use it in GitHub Desktop.
import PropTypes from 'prop-types';
type Omit<T, K> = Pick<T, Exclude<keyof T, K>>;
type Defined<T> = T extends undefined ? never : T;
/**
* Get the type that represents the props with the defaultProps included.
*
* Alternatively, we could have done something like this:
* ```
* export type WithDefaultProps<P, DP extends Partial<P>> = Omit<P, keyof DP> &
* Required<Pick<P, Extract<keyof DP, keyof P>>>;
* ```
* But there were usages of `null` in `defaultProps` that would need to be changed to `undefined`
* to meet the `DP extends Partial<P>` constraint.
* So, instead we take the union type in cases when a property in defaultProps does not extend
* the corresponding property in the Props declaration.
*/
type WithDefaultProps<P, DP> = Omit<P, keyof DP> &
{
[K in Extract<keyof DP, keyof P>]: DP[K] extends Defined<P[K]>
? Defined<P[K]>
: Defined<P[K]> | DP[K]
};
/**
* Get the props type from propTypes and defaultProps.
*
* Usage:
* ```
* // Without defaultProps
* type Props = PropsType<typeof propTypes>;
*
* // With defaultProps
* type Props = PropsType<typeof propTypes, typeof defaultProps>;
* ```
*/
export type PropsType<PT, DP = {}> = WithDefaultProps<PropTypes.InferProps<PT>, DP>;
@Wizyma
Copy link

Wizyma commented Jun 21, 2019

So cool !
Was looking at your conf, this will be very usefull, thanks !

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