Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
@flying-sheep
Copy link

flying-sheep commented Nov 10, 2021

@natterstefan
Copy link
Author

natterstefan commented Nov 10, 2021

I have an improvement of this here: busypeoples/6ac09e8dd63a12f78603fd76aa9cf580#gistcomment-3958014

Thanks for sharing your solution, @flying-sheep.

@flying-sheep
Copy link

flying-sheep commented Nov 11, 2021

No problem. The -? syntax was new for me so I’m happy I found something that is precise enough to do what I want.

@natterstefan
Copy link
Author

natterstefan commented Nov 29, 2021

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