study
[Typescript] <React.SetStateAction<type>> useState의 set함수 타입
시즈코
2022. 10. 13. 22:16
반응형
const [count, setCount] = useState(0)
typescript에서 다음과 같은 경우에는 useState를 통해 처음 정의해준 값이 0이기 때문에
count : number라는 것을 쉽게 알 수 있지만 setCount는 어떤 type인지 감이 안잡힌다.
드문드문 set함수의 type을 작성해야 하는 일이 있었는데 자주 사용하지 않으니깐 any를 써도 되지 않을까 싶어 지금까지 any를 사용했는데...
문제상황
// productContent.tsx
import React, { useState, useEffect } from 'react';
import ProductOrder from './productOrder';
function productContent() {
const [count, setCount] = useState(1);
return (
<>
<ProductOrder
setCount={setCount}
/>
</>
}
export default productContent;
// productOrder.tsx
function productOrder({ setCount } : { setCount : any }){
...
const handleMinus = () => {
if (count > 1) {
setCount(prev => {
return --prev;
});
setCartData(prev => {
return {
...prev,
quantity: --prev.quantity,
};
});
}
};
...
return(
...
)
}
위 코드의 prev에서
'prev' 매개 변수에는 암시적으로 'any' 형식이 포함됩니다.ts(7006)
오류가 났다.
해결방법
부모 component에서 prop을 하기 전 해당 함수에 마우스를 올려두면
이렇게 React.Dispatch<React.SetStateAction<number>>
type을 확인할 수 있다
그럼 해당 type을 복사해서 자식 component에 붙여넣기 해주면 된다!
그 외에도
매개변수가 없는 핸들러, 매개변수가 있는 핸들러는
() => void;
(e: any) => void;
type이 이렇게 나타난다.
마우스를 올려두었을 때 type을 그대로 작작성!
반응형