본문 바로가기
React

리액트) 타입스크립트에서 ...rest 사용

by se0nghyun2 2024. 5. 28.

 

배경

컴포넌트에서 받는 props의 양이 많았다. 

그렇다고 아래처럼 각각 모드 적어주자니 너무 비효율적이다.

interface IProps{
    children:React.ReactNode,
    label:string,
    name: string,
    ....
}

const RadioGroup = ({label,children,name,.................}:IProps) => {
	..
    return {
    	blabla
    }
}

 

 

 

해결

Rest Paramters

매개변수 수를 정해놓지 않고 사용자고 넣고 싶은 독립변수 수 만큼 도와주는 기능

 

위를 아래처럼 변경한다,

interface IProps{
    children:React.ReactNode,
    label:string,
    name: string,
}

const RadioGroup = ({label,children,name,...rest}:IProps) => {
	..
    return {
    	<div>
        	{rest.??}
        </div>
    }
}

 

 

추가)

참고로 타입스크립트를 사용하는 경우 인터페이스 선언 내부에 아래와 같이 추가 해주면 된다.

interface IProps{
    children:React.ReactNode,
    label:string,
    name: string,
    [key: string]: any;
}