- function arguments (eg.
onClick?: (event: React.MouseEvent<HTMLButtonElement, MouseEvent>) => void
vs.onClick: PropTypes.func.isRequired
) - not sure how to deal with eg.
interface IDeleteButtonProps extends IOtherInterface
with PropTypes
Last active
November 30, 2022 14:57
-
-
Save natterstefan/e67aad64cc72018fb96f35349e14d71d to your computer and use it in GitHub Desktop.
Typescript | Infere Types from PropTypes
This file contains hidden or 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, { FunctionComponent } from 'react' | |
import PropTypes from 'prop-types' | |
import { Button } from '@material-ui/core' | |
import DeleteIcon from '@material-ui/icons/Delete' | |
// PROPTYPES | |
const IDeleteButtonPropTypes = { | |
onClick: PropTypes.func.isRequired, | |
label: PropTypes.string, | |
} | |
const DeleteButtonDefaultProps = { | |
label: () => null, | |
} | |
// HELPER | |
type InferPropTypes< | |
PropTypes, | |
DefaultProps = {}, | |
Props = PropTypes.InferProps<PropTypes> | |
> = { | |
[Key in keyof Props]: Key extends keyof DefaultProps | |
? Props[Key] | DefaultProps[Key] | |
: Props[Key] | |
} | |
// OLD TS INTERFACE | |
// interface IDeleteButtonProps { | |
// label?: string | |
// onClick?: (event: React.MouseEvent<HTMLButtonElement, MouseEvent>) => void | |
// } | |
// NEW TS TYPE | |
type DeleteButtonProps = InferPropTypes< | |
typeof IDeleteButtonPropTypes, | |
typeof DeleteButtonDefaultProps | |
> | |
const RaDeleteButton: FunctionComponent<DeleteButtonProps> = ({ onClick, label }) => { | |
return ( | |
<Button | |
onClick={onClick} | |
startIcon={<DeleteIcon />} | |
> | |
{label} | |
</Button> | |
) | |
} | |
RaDeleteButton.propTypes = IDeleteButtonPropTypes | |
RaDeleteButton.defaultProps = DeleteButtonDefaultProps | |
export default RaDeleteButton |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I didn't know that either, thanks for making me aware of that.