Title: Add a --strictNaNChecks option, and a NaN / integer / float type to avoid runtime NaN errors · Issue #28682 · microsoft/TypeScript · GitHub
Open Graph Title: Add a --strictNaNChecks option, and a NaN / integer / float type to avoid runtime NaN errors · Issue #28682 · microsoft/TypeScript
X Title: Add a --strictNaNChecks option, and a NaN / integer / float type to avoid runtime NaN errors · Issue #28682 · microsoft/TypeScript
Description: I have read the FAQ and looked for duplicate issues. Search Terms NaN NaN type Integer type Related Issues #21279: strictNullChecks safeguards against null and undefined, but not NaN #15135: NaN, Infinity and -Infinity not accepted in nu...
Open Graph Description: I have read the FAQ and looked for duplicate issues. Search Terms NaN NaN type Integer type Related Issues #21279: strictNullChecks safeguards against null and undefined, but not NaN #15135: NaN, I...
X Description: I have read the FAQ and looked for duplicate issues. Search Terms NaN NaN type Integer type Related Issues #21279: strictNullChecks safeguards against null and undefined, but not NaN #15135: NaN, I...
Opengraph URL: https://github.com/microsoft/TypeScript/issues/28682
X: @github
Domain: github.com
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"Add a --strictNaNChecks option, and a NaN / integer / float type to avoid runtime NaN errors","articleBody":"*I have read the FAQ and looked for duplicate issues.*\r\n\r\n## Search Terms\r\n\r\n* NaN\r\n* NaN type\r\n* Integer type\r\n\r\n## Related Issues\r\n\r\n* [#21279: strictNullChecks safeguards against null and undefined, but not NaN ](https://github.com/Microsoft/TypeScript/issues/21279)\r\n* [#15135: NaN, Infinity and -Infinity not accepted in number literal types](https://github.com/Microsoft/TypeScript/issues/15135)\r\n * [#15351: Infinity/NaN literal type (dup)](https://github.com/Microsoft/TypeScript/issues/15351)\r\n* [#195: Suggestion: int type](https://github.com/Microsoft/TypeScript/issues/195)\r\n* [#4639: Proposal: int types](https://github.com/Microsoft/TypeScript/issues/4639)\r\n * BigInt is scheduled for TS 3.0 - [#15096 - Support for TC39 \"BigInt: Arbitrary precision integers in JavaScript\" proposal](https://github.com/Microsoft/TypeScript/issues/15096)\r\n\r\n## Suggestion\r\n\r\n`NaN` has been a big source of errors in my code. I was under the impression that TypeScript (and Flow) could help to prevent these errors, but this is not really true.\r\n\r\nTypeScript can prevent *some* `NaN` errors, because you cannot add a number to an object, for example. But there are many math operations that can return `NaN`. These `NaN` values often propagate through the code silently and crash in some random place that was expecting an integer or a float. It can be extremely difficult to backtrack through the code and try to figure out where the `NaN` came from.\r\n\r\nI would like TypeScript to provide a better way of preventing runtime `NaN` errors, by ensuring that an unhandled `NaN` value cannot propagate throughout the code. This would be a compile-time check in TypeScript. Other solutions might be a run-time check added with a Babel plugin, or a way for JS engines to throw an error instead of returning `NaN` (but these are outside the scope of this issue.)\r\n\r\n## Use Cases / Examples\r\n\r\n```js\r\nconst testFunction = (a: number, b: number) => {\r\n if (a > b) {\r\n return;\r\n } else if (a \u003c b) {\r\n return;\r\n } else if (a === b) {\r\n return;\r\n } else {\r\n throw new Error(\"Unreachable code\");\r\n }\r\n}\r\n\r\ntestFunction(1, 2);\r\n\r\ntestFunction(1, 0 / 0);\r\n\r\ntestFunction(1, Math.log(-1));\r\n\r\ntestFunction(1, Math.sqrt(-2));\r\n\r\ntestFunction(1, Math.pow(99999999, 99999999));\r\n\r\ntestFunction(1, parseFloat('string'));\r\n```\r\n\r\nA programmer might assume that the `Unreachable code` error could never be thrown, because the conditions appear to be exhaustive, and the types of `a` and `b` are `number`. It is very easy to forget that `NaN` breaks all the rules of comparison and equality checks.\r\n\r\nIt would be really helpful if TypeScript could warn about the possibility of `NaN` with a more fine-grained type system, so that the programmer was forced to handle these cases.\r\n\r\n### Possible Solutions \r\n\r\nTypeScript could add a `--strictNaNChecks` option. To implement this, I think TS might need to add some more fine-grained number types that can be used to exclude `NaN`. The return types of built-in JavaScript functions and operations would be updated to show which functions can return `NaN`, and which ones can never return `NaN`. A call to `!isNaN(a)` would narrow down the type and remove the possibility of `NaN`.\r\n\r\nHere are some possible types that would make this possible:\r\n\r\n```ts\r\ntype integer\r\ntype float\r\ntype NaN\r\ntype Infinity\r\n\r\ntype number = integer | float | NaN | Infinity // Backwards compatible\r\ntype realNumber = integer | float // NaN and Infinity are not valid values\r\n```\r\n(I don't know if `realNumber` is a good name, but hopefully it gets the point across.)\r\n\r\nHere are some examples of what this new type system might look like:\r\n\r\n```ts\r\nconst testFunction = (a: integer, b: integer) => {\r\n if (a > b || a \u003c b || a === b) {\r\n return;\r\n } else {\r\n throw new Error(\"Unreachable code\");\r\n }\r\n}\r\n\r\n// Ok\r\ntestFunction(1, 2);\r\n\r\n// Type error. TypeScript knows that a division might produce a NaN or a float\r\ntestFunction(1, 0 / 0);\r\n\r\nconst a: integer = 1;\r\nconst b: integer = 0;\r\n\r\nconst c = a + b; // inferred type is `integer`. Adding two integers cannot produce NaN or Infinity.\r\ntestFunction(1, c); // Ok\r\n\r\nconst d = a / b; // inferred type is `number`, which includes NaN and Infinity.\r\ntestFunction(1, d); // Type error (number is not integer)\r\n\r\nconst e = -2; // integer\r\nconst f = Math.sqrt(e); // inferred type is: integer | float | NaN (sqrt of an integer cannot return Infinity)\r\n\r\nconst g: number = 2; \r\nconst h = Math.sqrt(g); // inferred type is number (sqrt of Infinity is Infinity)\r\n\r\ntestFunction(1, h); // Type error. `number` is not compatible with `integer`.\r\n\r\nif (!isNaN(h)) {\r\n // The type of h has been narrowed down to integer | float | Infinity\r\n testFunction(1, h); // Still a type error. integer | float | Infinity is not compatible with integer.\r\n}\r\n\r\nif (Number.isInteger(h)) {\r\n // The type of h has been narrowed down to integer\r\n testFunction(1, h); // Ok\r\n}\r\n```\r\n\r\nWhen the `--strictNaNChecks` option is disabled (default), then the `integer` and `float` types would also include `NaN` and `Infinity`:\r\n\r\n```ts\r\ntype integer // Integers plus NaN and Infinity\r\ntype float // Floats plus NaN and Infinity\r\n\r\ntype number = integer | float // Backwards compatible\r\ntype realNumber = number // Just an alias, for forwards-compatibility.\r\n```\r\n\r\nI would personally be in favor of making this the default behavior, because `NaN` errors have caused me a lot of pain in the past. They even made me lose trust in the type system, because I didn't realize that it was still possible to run into them. I would really love to prevent errors like this at compile-time:\r\n\r\n\u003cimg width=\"446\" alt=\"screen shot 2018-11-27 at 4 35 34 pm\" src=\"https://user-images.githubusercontent.com/139536/49078834-aba8e900-f271-11e8-8bbe-15ae4ea7f930.png\">\r\n\r\nThis error is from a fully-typed Flow app, although I'm switching to TypeScript for any future projects. It's one of the very few crashes that I've seen in my app, but I just gave up because I have no idea where it was coming from. I actually thought it was a bug in Flow, but now I understand that type checking didn't protect me against `NaN` errors. It would be really awesome if it did! \r\n\r\n(Sorry for the Flow example, but this is a real-world example where a `NaN` type check would have saved me a huge amount of time.)\r\n\r\n## Number Literal Types\r\n\r\nIt would be annoying if you had to call `isNaN()` after every division. When the programmer calls `a / 2`, there is no need to warn about `NaN` (unless `a` is a `number` type that could potentially be `NaN`.) `NaN` is only possible for `0 / 0`. So if either the dividend or the divisor are non-zero numbers, then the `NaN` type can be excluded in the return type. And actually zero can be excluded as well, if both dividend and divisor are non-zero.\r\n\r\nMaybe this can be done with the `Exclude` [conditional type](https://www.typescriptlang.org/docs/handbook/advanced-types.html#conditional-types)? Something like:\r\n\r\n```ts\r\ntype nonZeroNumber = Exclude\u003cnumber, 0>\r\ntype nonZeroRealNumber = Exclude\u003crealNumber, 0>\r\ntype nonZeroInteger = Exclude\u003cinteger, 0>\r\ntype nonZeroFloat = Exclude\u003cfloat, 0>\r\n```\r\n\r\nIf the dividend and divisor type both match `nonZeroInteger`, then the return type would be `nonZeroFloat`. So you could test any numeric literal types against these non-zero types. e.g.:\r\n\r\n```\r\nconst a = 2; // Type is numeric literal \"2\"\r\n\r\n// \"a\" matches the \"nonZeroInteger\" type, so the return type is \"nonZeroFloat\" \r\n// (this excludes Infinity as well.)\r\n// (Technically it could be \"nonZeroInteger\", or even \"2\" if TypeScript did \r\n// constant propagation. But that's way outside the scope of this issue.)\r\nconst b = 4 / a;\r\n```\r\n\r\n## Checklist\r\n\r\nMy suggestion meets these guidelines:\r\n\r\n* [X] This wouldn't be a breaking change in existing TypeScript/JavaScript code\r\n* [X] This wouldn't change the runtime behavior of existing JavaScript code\r\n* [X] This could be implemented without emitting different JS based on the types of the expressions\r\n* [X] This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)\r\n* [X] This feature would agree with the rest of [TypeScript's Design Goals](https://github.com/Microsoft/TypeScript/wiki/TypeScript-Design-Goals).\r\n\r\n\r\n\r\n","author":{"url":"https://github.com/ndbroadbent","@type":"Person","name":"ndbroadbent"},"datePublished":"2018-11-27T11:13:26Z","url":"https://github.com/microsoft/TypeScript/issues/28682"}
| react-profiling | 0 |
| react-import-map | react,react-dom,react-dom/client,react-dom/profiling,react-is,react/compiler-runtime,react/jsx-dev-runtime,react/jsx-runtime,scheduler@b8488ee2c322 |
| route-pattern | /_view_fragments/issues/show/:user_id/:repository/:id/issue_layout(.:format) |
| route-controller | voltron_issues_fragments |
| route-action | issue_layout |
| fetch-nonce | v2:aaceccba-2843-428d-1f56-342ad44f4913 |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | 9254:76282:10A3AA1:171941B:6AFBFFA5 |
| html-safe-nonce | 2584f77117f7ca862eef84e8a665a0201fe79bf7e6b2feaac0906333fda6193f |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiI5MjU0Ojc2MjgyOjEwQTNBQTE6MTcxOTQxQjo2QUZCRkZBNSIsInZpc2l0b3JfaWQiOiI1Mzg3NDgyNTg3MDU0NDczMTI2IiwicmVnaW9uX2VkZ2UiOiJpYWQiLCJyZWdpb25fcmVuZGVyIjoiaWFkIn0= |
| visitor-hmac | 5a76d1dcf5754f2f1d8a8f8d2d301f19362f50d747a60192e0a636fb901bd53f |
| hovercard-subject-tag | issue:384743645 |
| github-keyboard-shortcuts | repository,issues,copilot |
| google-site-verification | Apib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I |
| octolytics-url | https://collector.github.com/github/collect |
| analytics-location | / |
| fb:app_id | 1401488693436528 |
| apple-itunes-app | app-id=1477376905, app-argument=https://github.com/_view_fragments/issues/show/microsoft/TypeScript/28682/issue_layout |
| twitter:image | https://opengraph.githubassets.com/56b087c74d55f5fb86be56f9b6a55d0348cd5669ff123f04d1bda5ee85af6744/microsoft/TypeScript/issues/28682 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/56b087c74d55f5fb86be56f9b6a55d0348cd5669ff123f04d1bda5ee85af6744/microsoft/TypeScript/issues/28682 |
| og:image:alt | I have read the FAQ and looked for duplicate issues. Search Terms NaN NaN type Integer type Related Issues #21279: strictNullChecks safeguards against null and undefined, but not NaN #15135: NaN, I... |
| og:image:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| og:author:username | ndbroadbent |
| hostname | github.com |
| expected-hostname | github.com |
| None | fa74413a1d84dac536fcca0740780bcbd3207bafec0e51873b73ff8e8cca032f |
| turbo-cache-control | no-preview |
| go-import | github.com/microsoft/TypeScript git https://github.com/microsoft/TypeScript.git |
| octolytics-dimension-user_id | 6154722 |
| octolytics-dimension-user_login | microsoft |
| octolytics-dimension-repository_id | 20929025 |
| octolytics-dimension-repository_nwo | microsoft/TypeScript |
| octolytics-dimension-repository_public | true |
| octolytics-dimension-repository_is_fork | false |
| octolytics-dimension-repository_network_root_id | 20929025 |
| octolytics-dimension-repository_network_root_nwo | microsoft/TypeScript |
| turbo-body-classes | logged-out env-production page-responsive |
| disable-turbo | false |
| browser-stats-url | https://api.github.com/_private/browser/stats |
| browser-errors-url | https://api.github.com/_private/browser/errors |
| release | b3b5633a74535d9c23385512d534c66c8fde1907 |
| ui-target | canary-1 |
| theme-color | #1e2327 |
| color-scheme | light dark |
| react-app-name | issues |
Links:
Viewport: width=device-width