Category: Next.js, React and TypeScript

TypeScript TS2322: String Is Not Assignable to Number

Read this guide in Polish

After reading the numeric field from HTML TypeScript does not allow to assign its value to the number. Value input.value is a string regardless of type="number", and an empty entry does not represent the correct number.

How to identify the source of the problem

Check event.currentTarget.value types and expected business model type. Test empty input, comma value and normal number to determine parsing rules.

Compare the message from the console with the result of the production compilation and the condition after the page has been refreshed.

Repair steps

Perform a public parsing Number or valueAsNumber and NaN and no number of service in validation form. Separate the string type used to enter data from the number type saved after successful validation.

How to Test Solution

The figures do not contain NaN and the incorrect entry displays the information instead of a silent conversion to zero.

Security and restrictions

Do not force the number type by as number on the string, because it does not convert values.