반응형
React + Typescript 환경에서
error TS2322: Type 'Timeout' is not assignable to type 'number'
해결 방법
setTimeout을 쓸때 useRef에 setTimeout의 return 값을 저장해야 됩니다.
const timeoutId = useRef<number | undefined>()
timeoutId.current = setTimeout(() => {
setVisible(false)
}, timeoutMilliSeconds)
이런식으로 useRef의 제네릭 타입을 지정하게 되면 위와 같은 에러가 발생합니다.
const timeoutId = useRef<ReturnType<typeof setTimeout> | undefined>()
이렇게 useRef의 제너릭 타입을 setTimeout의 ReturnType으로 지정해주면 해결 됩니다.
반응형
'개발관련 > 자바스크립트 팁' 카테고리의 다른 글
자바스크립트의 반복문 종류 및 사용법: for, for...in, for...of, forEach (0) | 2023.04.26 |
---|---|
자바스크립트 배열 유니크 요소만 남기기 , 중복 제거 하기 (0) | 2023.04.13 |
yarn pnp Zero-Installs란? (0) | 2022.09.15 |
yarn pnp vscode typescript 적용하는 방법 (0) | 2022.09.15 |
yarn2 ( yarn berry )와 함께 PnP(Plug'n'Play)를 적용해보기 고통스러운 node_modules 탈출 하기 (0) | 2022.09.15 |