Resolving TypeScript Typing Issue with Custom Hook in React

Asked 1 year ago

1 Vote

0 Answers

11 Views

In my React project with TypeScript, I've created a custom hook for form handling, but I'm encountering a TypeScript error with the hook's return type. The issue arises when I try to use the hook in a component, where TypeScript is unable to correctly infer the type of the returned form data. Here's the code for the custom hook and its usage:

import { useState } from 'react';

interface FormData {
    name: string;
    age: number;
}

function useForm<T>(initialValues: T) {
    const [values, setValues] = useState<T>(initialValues);

    const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
        setValues({
            ...values,
            [event.target.name]: event.target.value
        });
    };

    return { values, handleChange };
}

// Usage in a component
const MyFormComponent: React.FC = () => {
    const { values, handleChange } = useForm<FormData>({ name: '', age: 0 });

    return (
        <form>
            <input
                name="name"
                value={values.name}
                onChange={handleChange}
            />
            <input
                name="age"
                type="number"
                value={values.age}
                onChange={handleChange}
            />
        </form>
    );
};


The TypeScript error occurs in the component, stating that the values object does not have the properties name and age. I'm not sure how to properly type the useForm hook or its return value to resolve this error. Could someone help me understand the correct way to type this custom hook for it to work seamlessly with the component?

No answers yet, be the first one to answer!

Write your answer here

Top Questions