programing

TypeScript를 사용한 함수 파라미터의 소품 파괴

elseif 2023. 3. 15. 19:23

TypeScript를 사용한 함수 파라미터의 소품 파괴

TypeScript를 사용하기 위해 컴포넌트 라이브러리에 접속하여 Respect의 스테이트리스 기능 컴포넌트를 ES6/JavaScript에서 TypeScript로 변환하려고 합니다.기능 외의 소품도 파라미터를 전달하면서 분해할 수 있는데 어떻게 하면 중복을 피할 수 있을까 고민입니다.

현재 컴포넌트는 다음과 같습니다.

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
};

이를 TypeScript에 리팩터링하려면 어떻게 해야 합니까?

type Color = "warning" | 'info'| 'success' | 'danger'

interface IProps {
  color: Color
}

const AlertIcon = ({ className, color, ...props }: IProps) => { ... }

사용할 때AlertIconcolor소품은 종류여야 합니다.Color

HTML 속성 전달을 고려합니다.className다음과 같이 할 수 있습니다.

interface IProps extends HTMLAttributes<HTMLElement> { ... }

어디에HTMLElement사용자 타입의 요소입니다.

언급URL : https://stackoverflow.com/questions/52600056/destructuring-props-in-the-function-parameters-using-typescript