Source:  Twitter logo

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?

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.

67 users liked answer #0dislike answer #067
Uzi profile pic
Uzi

Copyright © 2022 QueryThreads

All content on Query Threads is licensed under the Creative Commons Attribution-ShareAlike 3.0 license (CC BY-SA 3.0).