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) => { ... }
사용할 때AlertIcon
그color
소품은 종류여야 합니다.Color
HTML 속성 전달을 고려합니다.className
다음과 같이 할 수 있습니다.
interface IProps extends HTMLAttributes<HTMLElement> { ... }
어디에HTMLElement
사용자 타입의 요소입니다.
언급URL : https://stackoverflow.com/questions/52600056/destructuring-props-in-the-function-parameters-using-typescript
'programing' 카테고리의 다른 글
리액트 후크 : 하위 컴포넌트에서 상위 컴포넌트로 데이터를 전송합니다. (0) | 2023.03.15 |
---|---|
반응 - 상태가 업데이트되지 않음 (0) | 2023.03.15 |
셸 스크립트의 JSON 어레이를 통한 반복 (0) | 2023.03.15 |
sysdate에서 년을 빼는 방법 (0) | 2023.03.15 |
Jackson 및 WebClient를 사용하여 json 어레이를 개체로 역직렬화 (0) | 2023.03.10 |