I'm trying to my component library to use TypeScript and am attempting to convert a stateless functional component in React from ES6/JavaScript to TypeScript. I am wondering how I can avoid duplicating myself while still being able to deconstruct props outside the function while passing it parameters.
My component currently looks like this:
const allowedColors = { warning: "fa fa-exclamation", info: "fa fa-info", success: "fa fa-check", danger: "fa fa-minus-circle" }; const AlertIcon = ({ className, color, ...props }) => ( <FontAwesomeIcon {...props} iconClassName={allowedColors[color]} className={classNames(`alert-icon-${color}`, className)} aria-hidden="true" data-ut="alert-icon" /> ); AlertIcon.propTypes = { className: PropTypes.string, color: PropTypes.oneOf(Object.keys(allowedColors)).isRequired };
How would I go about refactoring this into TypeScript?
When destructuring object parameters in a function, separate the destructured parameters and the type for the specific properties with a colon, e.g. function getPerson({ name, age }: { name: string; age: number }) {} .
You can destructure the React props object within the render method inside a React class component. You can also destructure the React props object within a React functional component.
To pass a function as props in React TypeScript: Define a type for the function property in the component's interface. Define the function in the parent component. Pass the function as a prop to the child component.
type Color = "warning" | 'info'| 'success' | 'danger' interface IProps { color: Color } const AlertIcon = ({ className, color, ...props }: IProps) => { ... }
now when you use AlertIcon
the color
prop must be of type Color
to account for passing HTML attributes, like className
you can do this:
interface IProps extends HTMLAttributes<HTMLElement> { ... }
where HTMLElement
is your type of element.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With