2

I write a custom hook for handle input in my app. I use generic type to define what type return for my custom hook. Here is my code

interface IUseInput<T, U> {
    (): [T, (e: ChangeEvent<HTMLInputElement>) => void, U];
}

function useInput<T, U>(): IUseInput<T, U> {
    const [input, setInput] = useState({});
    const [isDirty, setDirty] = useState({});

    const handleInputChange = (e: ChangeEvent<HTMLInputElement>) => {
        setInput({
            ...input,
            [e.target.name]: e.target.value
        });
        setDirty({
            ...isDirty,
            [e.target.name]: true
        });
    };

    return [input, handleInputChange, isDirty] //this line get error
}


const Component: React.FC = () => {
    const [input, handleChangeInput, isDirty] = useInput<{username: string, password: string}, {username: boolean, password: boolean}>();

  return (
      ....
  )

}

But I get this error Type '{}[]' is not assignable to type 'IUseInput<T, U>

WHere is my wrong? Please help me

1 Answer 1

2

IUseInput<T, U> is the type of the function, not the type of the return type. There is no way to specify the type of a function declaration, only the type of a variable (to which you could assign a function). However this is not really necessary, I would just move the return type from IUseInput to the function declarartion.

An improvement that could be made, since U should have the same keys as T you can derive U from T using the predefined mapped type Record. So you can replace U with Record<keyof T, boolean>:

function useInput<T>(): [T, (e: ChangeEvent<HTMLInputElement>) => void, Record<keyof T, boolean>] {
    const [input, setInput] = useState({} as T);
    const [isDirty, setDirty] = useState({} as Record<keyof T, boolean>);

    const handleInputChange = (e: ChangeEvent<HTMLInputElement>) => {
        setInput({
            ...input,
            [e.target.name]: e.target.value
        });
        setDirty({
            ...isDirty,
            [e.target.name]: true
        });
    };

    return [input, handleInputChange, isDirty] 
}

Playground Link

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.