TS custom hook useInput 와 TextInput 타입 맞추기

Maliethy·2021년 3월 31일

1. issue

custom hook useInput의 타입으로 인해 TextInput에 다음과 같은 No overload matches this call type error가 발생했다.

No overload matches type error

No overload matches this call.
  Overload 2 of 2, '(props: TextInputProps, context: any): TextInput', gave the following error.
    Type 'string | Dispatch<SetStateAction<string | null>> | null' is not assignable to type 'string | undefined'.
  Overload 2 of 2, '(props: TextInputProps, context: any): TextInput', gave the following error.
    Type 'string | Dispatch<SetStateAction<string | null>> | null' is not assignable to type '((text: string) => void) | undefined'.

custom hook인 useInput의 타입은 다음과 같다.

 const [detailedAddr, onChangeDetailedAddr, onResetDetailedAddr, setDetailedAddr] = useInput('');
 
   <TextInput
                value={detailedAddr}
                onChangeText={onChangeDetailedAddr}
                ref={ref_input}
                placeholder="상세주소를 입력해주세요"
              />

2. solution

unknown, undefined, any, void의 차이를 공식문서를 보며 다시 확인해보며 useInput의 return값을 unknown, null, undefined, string | Dispatch<SetStateAction<string | null>> | null 등등 모두 시도해봤으나
useInput의 return값을 any로 했을 때에만 type error가 사라졌다.

import { useState, useCallback } from 'react';

const useInput = (initialValue: null | string): any => {
  const [value, setValue] = useState(initialValue);
  const onChangeText = useCallback((e) => {
    setValue(e);
  }, []);
  const onResetText = useCallback(() => {
    setValue('');
  }, []);
  return [value, onChangeText, onResetText, setValue];
};
export default useInput;

또한 .eslintrc.js에서 '@typescript-eslint/no-unsafe-assignment',
'@typescript-eslint/no-unsafe-call'의 설정을 꺼두어 any로 인한 경고줄을 감추었다.

{
  ...
 '@typescript-eslint/no-unsafe-assignment': 'off',
 '@typescript-eslint/no-unsafe-call': 'off',
 ...
 }
profile
바꿀 수 있는 것에 주목하자

0개의 댓글