Subscribe on changes!

Returning "" instead null when use v-model.number

avatar
May 2nd 2023

Vue version

3.2.47

Link to minimal reproduction

https://codepen.io/leo-bnu/pen/rNqGqWJ

Steps to reproduce

  1. Access https://codepen.io/leo-bnu/pen/rNqGqWJ
  2. Clear the field
  3. Check the returned value

What is expected?

The returned value should be null.

What is actually happening?

The returned value is "".

System Info

No response

Any additional comments?

No response

avatar
May 3rd 2023

Why should it be null?

avatar
May 3rd 2023

Hi @LinusBorg

Retuning a number as string, is not a good practice and may cause some side effects:

  1. Changing type at runtime is not a good practice (and breaks the Typescript type previously defined)
  2. If you have to calculate, all calculated values will be string, it's like a virus
  3. If you have to send back the value to an API, it may reject because string is not a number
  4. Add a lot of code to convert the value from string to number

Why use null instead?

  1. No type change at runtime, seems a good practice
  2. If you have to calculate, all calculated values will be number
  3. If you send back the value to API, it will work
  4. Save a lot of code, you do not need to convert the string to number anymore
  5. It has a better DX

Explaining better the (2) point:

1 + "" + 1 = "11" // bad
1 + 1 + "" = "2" // bad
1 + null + 1 = 2 // good
1 + 1 + null = 2 // good

In my opinion there are no reason to return "". I will understand if this is a breaking change. At a first moment I can't see what will break with this change.

avatar
May 12th 2023

I just fell into this bug as well.

I expected null. The "" makes the value a string. This means at runtime the variable is effectively number | string instead of number or number | null.

avatar
May 12th 2023

Also, the <input type="number"> in vanilla JS has .value and .valueAsNumber that returns "" and null on empty fields. Would be nice to have the same behavior here.

avatar
May 12th 2023

Also, the <input type="number"> in vanilla JS has .value and .valueAsNumber that returns "" and null on empty fields. Would be nice to have the same behavior here.

Amending my comment that I'm also seeing this in <input type="number">.

avatar
May 19th 2023

@TheSeg @leonardorafael .valueAsNumber returns a NaN for me

avatar
May 19th 2023

Hi, I made a codepen in vanilla JS and returns null (tested in Chrome).

https://codepen.io/leo-bnu/pen/KKGrXxv

image image image

avatar
May 19th 2023

@leonardorafael that's because NaN is transformed to null in JSON.stringify

avatar
May 19th 2023

@leonardorafael that's because NaN is transformed to null in JSON.stringify

True, living and learning