Created
March 9, 2019 22:50
-
-
Save busypeoples/6ac09e8dd63a12f78603fd76aa9cf580 to your computer and use it in GitHub Desktop.
Infer Props using PropTypes.InferProps
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 React from "react"; | |
import { render } from "react-dom"; | |
import PropTypes from "prop-types"; | |
// Using PropTypes.InferProps | |
type InferPropTypes< | |
PropTypes, | |
DefaultProps = {}, | |
Props = PropTypes.InferProps<PropTypes> | |
> = { | |
[Key in keyof Props]: Key extends keyof DefaultProps | |
? Props[Key] | DefaultProps[Key] | |
: Props[Key] | |
}; | |
// Test | |
const userPropTypes = { | |
id: PropTypes.number.isRequired, | |
name: PropTypes.string.isRequired, | |
active: PropTypes.bool | |
}; | |
const userDefaultProps = { | |
name: "Test" | |
}; | |
type ActionProps = InferPropTypes< | |
typeof userPropTypes, | |
typeof userDefaultProps | |
>; | |
/* | |
type ActionProps = { | |
id: number; | |
name: string; | |
active?: boolean; | |
} | |
*/ | |
const Action = (props: ActionProps) => { | |
return ( | |
<div> | |
id: {props.id} | |
name: {props.name} | |
status: {props.active ? "active" : "inactive"} | |
</div> | |
); | |
}; | |
Action.defaultProps = userDefaultProps; | |
render(<Action id={1} />, document.getElementById("root")); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Improvement to not add spurious nulls (for strict null checks):
-?
makes it so props aren’t automatically unified with| undefined
NonNullable
makes it so that only if the defaultProps entry isnull
orundefined
will the actual type be null. This enables e.g.:ideal also for js migration!
helpers.d.ts
SomeComponent.js