IT 일기장

[React] 변수 타입 설정 본문

프로그래밍 언어/React

[React] 변수 타입 설정

뽕슈 2021. 12. 1. 11:05
반응형

코레일 프로젝트를 진행하면서 React에 대한 업무도 맡게됐는데.. 맨땅에 헤딩중이다.

월을 선택할때마다 일 수가 바뀌는 기능을 만들었는데 내 코드는 다음과 같았다.

 

const changeMonth = (e) => {
    setDayList([]);
    let month = e.target.value;
    setSelctedMonth(month);
    let lastday = new Date(SelectedYear, month, 0).getDate();
    let array = [];
    for(let i=1 ; i <= lastday ; i++){
    	array.push(i);
    }
    setDayList(array);
}

 

근데 이상하게도 array.push(i) 구문 i에서 에러 표시가 난다.

궁금해서 React 현업 개발자에게 물어보니 i가 number라 배열 타입을 맞춰줘야 된다고 한다.

 

const changeMonth = (e) => {
    setDayList([]);
    let month = e.target.value;
    setSelctedMonth(month);
    let lastday = new Date(SelectedYear, month, 0).getDate();
    let array : any[] = [];
    for(let i=1 ; i <= lastday ; i++){
    	array.push(i);
    }
    setDayList(array);
}

 

number만 가능하게 하고 싶으면 : number[]

string만 가능하게 하고 싶으면 : string

어떤 타입이든 가능하게 하고 싶으면 : any[]

 

반응형
Comments