'react-form-hook: useForm data not matching TypeScript type, but no errors
I'm trying to validate a form using react-hook-form.
My code below is working fine, but as you can see Person.name is of type string; submitting the form results in
data = { name: 2 },
i.e. data.name is of type number. Why am I not getting a type error inside the onSubmit function? For me this was the whole point of using TypeScript in the first place...
Am I missing something, or do I really have register a (duplicate) validation method for my input (via useForm)?
Here is the piece of code that I would expect to break:
...
const onSubmit = (data: Person) => {
console.log({ data });
};
...
Note that I'm setting valueAsNumber = true, see here useform/register; this is working properly as data.name is a number.
import { useForm } from "react-hook-form";
type Person = {
name: string;
};
const PersonForm = () => {
const { register, handleSubmit, formState: { errors } } = useForm<Person>();
const onSubmit = (data: Person) => {
console.log({ data });
};
console.log({ errors });
return (
<form onSubmit={handleSubmit(onSubmit)}>
<div className="field">
<label htmlFor="name">Name</label>
<input
defaultValue="2"
type="text"
{...register("name", { required: true, valueAsNumber: true })}
/>
</div>
<button type="submit">Save</button>
</form>
);
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
