type-fest icon indicating copy to clipboard operation
type-fest copied to clipboard

Float type does not allow whole number floats

Open mattdiamond opened this issue 4 years ago • 2 comments

The new Float type does not type-check with values like 1.0, 2.0, etc. Is this the intended behavior?

It appears that these values are being converted to integers and therefore type-check with the Integer type, which prevents them from type-checking as Float.

Example: https://www.typescriptlang.org/play?#code/C4TwDgpgBAkgdsCBzCAnAPAFShAHouAEwGco4BXAWwCM0A+KAXigAMASAb0wF8Wd8IRUuw7UAlkjEJeUAPxRsALjIQAbmgDcAWABQoSFABiAGwD2AQ2BZ+BEmSq1UDZtjy3S8RCgyYG8uGpoUMqY2jq6AGbkcADGwGKmcFCU5MbxYMYg1m6CdhQ09AAUuMomFla+ADRQIKVmllh0AJTK+Y5QHLpQUKgQwOSoSbhQAFQ1Ydy6uilpYhkghQDMAHQAjNUALMsADE0aQA

mattdiamond avatar Dec 03 '21 19:12 mattdiamond

// @jonahsnider

sindresorhus avatar Dec 03 '21 19:12 sindresorhus

All numeric types operate on the value of the number, not the specific way it was defined. This means TypeScript treats 4.0 and 4 as the same type, so this would be considered intended behavior.

This is also how JavaScript engines work themselves, 4.0 and 4 are both going to be normalized into the same value during the parse step.

If having a strong distinction between floats and ints is important for you I'd recommend one of the following:

  • Refactor your codebase to use bigints for ints and numbers for floats.
  • Use Opaque to create your own integer & float types.

jonahsnider avatar Dec 03 '21 22:12 jonahsnider