🔥 문제
타입스크립트로 컴포넌트 타입을 설정하는 데 있어 고민이 생겼다.
만약 n번째 배열의 값과 m번째 배열의 값을 타입을 지정해주고 싶다면 어떻게 해야할까?
객체의 경우 간단하게 인터페이스던지, 타입이던지 간에 설정해주면 그만인데, 배열은 좀 다른 느낌이었다.
어떻게 해결할 수 있을까?
⭐ 해결 방법
1. 배열 + 타입 단언
가. 먼저 배열에 들어갈 수 있는 타입 값 지정
다음과 같이 배열에 들어갈 수 있는 타입 값을 지정해주었다.
export type callbackType = () => void; export type buttonArrType = (string | callbackType)[];
나. 타입 추론 시 오류가 발생하는 부분에 타입 단언
개발자가 타입스크립트에게 타입을 단언해줌으로써, 보수적인 타입 추론을 해소시켜줌으로써 타입 오류를 피할 수 있다.
<StyledSortButtons width={width}> {buttonArr.map(([name, cb]: buttonArrType) => ( <Button key="name" buttonType="primary" fontSize={14} onClick={cb as callbackType} reversal bold={false} backgroundColor="white" color="black" > {name} </Button> ))} </StyledSortButtons>
2. 튜플을 사용
현재 배열은 길이가 정해져 있다. 따라서 타입스크립트 핸드북에 적힌 튜플을 사용해보도록 하자.
튜플이란, 쉽게 말해서, 길이가 정해져 있는 배열이라 보면 되겠다.
import Button from '@components/atoms/Button'; import styled from '@emotion/styled'; import React from 'react'; export type widthType = string | number; export type callbackType = () => void; export type buttonArrType = [string, callbackType]; export interface SortButtonsProps { width: widthType; [prop: string]: any; } const StyledSortButtons: React.FC<SortButtonsProps> = styled.section` display: flex; justify-content: space-between; width: ${({ width }: { width: widthType }) => typeof width === 'string' ? width : `${width}px`}; `; const SortButtons = ({ width, buttonArr }: SortButtonsProps) => { if (!buttonArr.length) return null; return ( <StyledSortButtons width={width}> {buttonArr.map(([name, cb]: buttonArrType) => ( <Button key="name" buttonType="primary" fontSize={14} onClick={cb} reversal bold={false} backgroundColor="white" color="black" > {name} </Button> ))} </StyledSortButtons> ); }; export default SortButtons;
결과
오류가 나지 않는다 🙂
