How to satisify TypeScript when assigning defaultValue of ''
empty string to a number
field?
#10526
-
I want the number input to have no value by default. const { control } = useForm<{ price: number }>({
defaultValue: {
price: ''
// TS2322: Type 'string' is not assignable to type 'number'.
}
} Although I can use Below are what I've tried:
|
Beta Was this translation helpful? Give feedback.
Replies: 3 comments
-
The first generic argument is your form dirty field values, and third is Ttransformed/valid values that get as first argument into you submit handler. So try this: useForm<{ price: number | string }, void, { price: number }> |
Beta Was this translation helpful? Give feedback.
-
Where you able to find a solution? I have the same question. But I am defining my form Schema using Zod
|
Beta Was this translation helpful? Give feedback.
-
In Zod v4, it seems that import { z } from "zod/v4";
const schema = z.object({
price: z.coerce.number("notGreaterThanZero").gt(0, "notGreaterThanZero"),
});
type ISchema = z.input<typeof schema>; // Use the input type
function Example() {
const {
register,
handleSubmit,
formState: { errors, isDirty },
} = useForm<ISchema>({
resolver: standardSchemaResolver(schema),
defaultValues: { price: "" },
});
function onSubmit(data: ISchema) {
const coercedData = schema.parse(data); // Retrieve the coerced data (z.infer type)
console.log(coercedData);
}
return (
<form onSubmit={handleSubmit(onSubmit)}>
<div>Dirty: {isDirty ? "true" : "false"}</div>
<div>{JSON.stringify(errors.price?.message)}</div>
<input type="number" {...register("price")} />
<button>Submit</button>
</form>
);
} |
Beta Was this translation helpful? Give feedback.
The first generic argument is your form dirty field values, and third is Ttransformed/valid values that get as first argument into you submit handler. So try this: