[TIL] 231022

이세령·2023년 10월 21일
0

TIL

목록 보기
112/118

TypeScript

Error

type 'string | Dispatch<SetStateAction<string>> | ((e: ChangeEvent<HTMLInputElement> | ChangeEvent<HTMLTextAreaElement>) => void)' is not assignable to type 'string | number | readonly string[] | undefined'. Type 'Dispatch<SetStateAction<string>>' is not assignable to type 'string | number | readonly string[] | undefined'.
useInput을 커스텀 훅으로 전환하는 과정에서 반환 타입을 명확하게 지정하지 않아 발생하는 오류이다.

import { useState } from 'react';

const useInput = () => {
// state
const [value, setValue] = useState<string>('');

// handler
const handler = (e: React.ChangeEvent<HTMLInputElement> | React.ChangeEvent<HTMLTextAreaElement>) => {
  setValue(e.target.value);
};
return [value, handler, setValue] as const;
};

export default useInput;

as const를 사용하여 반환 타입을 명시적으로 지정해줌으로써 오류를 해결할 수 있다.

profile
https://github.com/Hediar?tab=repositories

0개의 댓글