Skip to content

Instantly share code, notes, and snippets.

@natterstefan
Last active November 30, 2022 14:57
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save natterstefan/e67aad64cc72018fb96f35349e14d71d to your computer and use it in GitHub Desktop.
Save natterstefan/e67aad64cc72018fb96f35349e14d71d to your computer and use it in GitHub Desktop.
Typescript | Infere Types from PropTypes
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
@natterstefan
Copy link
Author

I didn't know that either, thanks for making me aware of that.

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