Title: #AvoidTheVoid Allow users to avoid the `void` type. · Issue #42709 · microsoft/TypeScript · GitHub
Open Graph Title: #AvoidTheVoid Allow users to avoid the `void` type. · Issue #42709 · microsoft/TypeScript
X Title: #AvoidTheVoid Allow users to avoid the `void` type. · Issue #42709 · microsoft/TypeScript
Description: Suggestion Allow developers to avoid the void type. I’d like to propose a couple changes to TypeScript to make void an optional type, and infer undefined in more places where void is currently used. I’ve argued in multiple places that Ty...
Open Graph Description: Suggestion Allow developers to avoid the void type. I’d like to propose a couple changes to TypeScript to make void an optional type, and infer undefined in more places where void is currently used...
X Description: Suggestion Allow developers to avoid the void type. I’d like to propose a couple changes to TypeScript to make void an optional type, and infer undefined in more places where void is currently used...
Opengraph URL: https://github.com/microsoft/TypeScript/issues/42709
X: @github
Domain: github.com
IPv4 address: 140.82.113.3
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"#AvoidTheVoid Allow users to avoid the `void` type.","articleBody":"# Suggestion\nAllow developers to avoid the `void` type.\n\n\n\nI’d like to propose a couple changes to TypeScript to make `void` an optional type, and infer `undefined` in more places where `void` is currently used. I’ve argued in multiple places that TypeScript’s `void` type is confusing and detrimental to development, and I was asked by a maintainer to create the following document to outline the problems with `void` and propose potential solutions.\n\n## The Problem\n\nFirst, what is `void`? According to [the TypeScript handbook](https://www.typescriptlang.org/docs/handbook/basic-types.html#void):\n\n> void is a little like the opposite of any: the absence of having any type at all. You may commonly see this as the return type of functions that do not return a value.\n\nIn practice, the `void` type is more or less a black hole kind of type. Nothing is assignable to `void` except itself, `undefined` and `any`, and `void` is not assignable to anything except itself, `unknown` and `any`. Additionally, typical type narrowings like `typeof x === \"string\"` do not narrow `void`, and `void` infects type unions like `void | string` by making the resulting type behave like `void`.\n\nThe handbook hints at the original use-case for void, which is that it was used to model functions which don’t return, i.e. functions without a `return` statement. Although the runtime behavior of these functions is to return `undefined`, maintainers argued for modeling these functions as returning `void` instead at the type level because implicit return values are seldom used, and if they are used this usually indicates some kind of programmer error. The reasoning was that if you actually wanted a function to have a return type of `undefined`, you could do so by explicitly returning `undefined` from the function.\n\nThis section of the TypeScript handbook is a good start, but it doesn’t fully address the intricacies of the `void` type. While `void` behaves mostly like a special type alias for `undefined` when used in typical assignments, it behaves more like `unknown` when used as the return type of a function type (`() => void`).\n\n```ts\n // these functions should return implicitly or will error\nfunction fn1(): void {}\nconst fn2 = (): void => {};\n\n// only undefined or void can be assigned to void variables\nconst v: void = undefined;\n\n// void in function types behaves like unknown insofar as it allows the assigned function to return anything\nconst callback: () => void = () => 1337;\n```\n\nAgain, this makes sense according to the original motivations for void: if you’re marking a callback’s return type as void, then you don’t really care what the callback returns, because you’ve essentially promised that you’ll never use it. It’s important to note that `void` came very early in TypeScript’s development, and neither the `unknown` type nor even strict null checks existed at its point of creation.\n\nUnfortunately, this dual nature of `void` as being either `undefined` or `unknown` based on its position has an undesirable consequence, which is that while `undefined` is always assignable to `void`, `void` is not assignable to `undefined`. Personally, I noticed this issue with increasing frequency because of my work with async and generator functions, to the point where I felt that the `void` type was getting in my way. These function syntaxes also did not exist when the `void` type was created, and their very existence violates the key assumption which motivated the creation of the `void` type in the first place, that we don’t or shouldn’t use the return values of functions with implicit returns.\n\nThis assumption collapses when we consider async and generator functions because we more or less *must* use the return values of async and generator functions even if they return implicitly. Many async functions have implicit returns, where the function body is used to await other promises, and the vast majority of generator functions do not contain return statements at all. Despite this, it would be a basic programmer error not to use the returned promises or generator objects in some way, so much so that there are even lint rules like `no-floating-promise` to prevent you from ignoring the return values of these types of functions.\n\nBecause we must use the return values of async and generator functions, and because they are inferred to return compositions of `void` like `Promise\u003cvoid>` or `Generator\u003cany, void>`, `void` types inevitably leak into assignments. I have frequently been frustrated by attempts to assign `Promise\u003cvoid>` to `Promise\u003cundefined>`, or `Generator\u003cany, void>` to `Generator\u003cany, undefined>`; invariably, the error pyramids which TypeScript emits all end with `void` not being assignable to `undefined`.\n\n```ts\nclass Example {\n _initPromise: Promise\u003cundefined>;\n\n async initialize() {\n // some async setup code\n // no explicit return\n }\n\n constructor() {\n // A compiler error because initialize is inferred to return Promise\u003cvoid>.\n this._initPromise = this.initialize();\n }\n}\n\nfunction *integers() {\n let i = 0;\n while (true) {\n yield i++;\n }\n}\n\n// A compiler error because value is inferred as number | void.\nconst value: number | undefined = integers().next().value;\n```\n\nThe TypeScript lib definitions also leak void into assignments, with `Promise.resolve()` called with no arguments being inferred as `Promise\u003cvoid>`, and the promise constructor explicitly requiring `undefined` to be passed to the `resolve()` function if the promise’s type parameter is `undefined` and not `void`.\n\nAll these details make trying to avoid `void` painful, almost impossible. We could explicitly `return undefined` from all non-returning functions and call `Promise.resolve(undefined)` to create a non-void Promise, but this violates one of the main goals of TypeScript, which is to produce idiomatic JavaScript. Moreover, it is not a workable solution for library authors who wish to avoid the `void` type, insofar as it would require libraries to impose the same requirements of explicit usages of `undefined` on their users.\n\nHere’s the thing. If we were to do a survey of all the places where the `void` type is currently inferred, I would estimate that in >95% of these positions, the actual runtime value is always `undefined`. However, because we can’t eliminate the possibility that `void` is being used like `unknown`, we’re stuck leaving the voids in place. In essence, TypeScript is not providing the best possible inference for code wherever `void` is inferred. It’s almost as if TypeScript is forcing a nominal type alias for `undefined` on developers, while most TypeScript typing is structural.\n\nBeyond producing unnecessary semantic errors, the `void` type is very confusing for JavaScript developers. Not many developers distinguish the return type of function declarations from the return type of function types as two separate type positions, and `void` is (probably?) the only type whose behavior differs based on its usage in these two places. Furthermore, we see evidence of this confusion whenever people create unions with `void` like `Promise\u003cvoid> | void` or `void | undefined`. These union types are mostly useless, and hint that developers are just trying to get errors to go away without understanding the vagueries of void.\n\n## The Solution\n\nTo allow the void type to be optional, I propose we make the following changes to TypeScript.\n\n### Allow functions which have a return type of undefined or unknown to return implicitly.\n\n```ts\n// The following function definitions should not cause compiler errors\nfunction foo(): undefined {\n}\n\nfunction bar(): unknown {\n}\n\nasync function fooAsync(): Promise\u003cundefined> {\n}\n\nfunction *barIterator(): Generator\u003cany, unknown> {\n}\n```\n\nCurrently, attempting to type the return types of functions with implicit returns as `undefined` or `unknown` will cause the error `A function whose declared type is neither 'void' nor 'any' must return a value.` The `any` type is unacceptable because it makes functions with implicit returns type-unsafe, so we’re left with `void`. By allowing `undefined` or `unknown` returning functions to return implicitly, we can avoid `void` when typing implicitly returning functions.\n\nThis behavior should also extend to async and generator functions.\n\nRelated proposal https://github.com/microsoft/TypeScript/issues/36288\n\n### Infer functions with implicit returns and no return type as returning undefined.\n\nThere are many situations where we would rather not have `void` inferred. For instance, when using anonymous callbacks with promises, we can unwittingly transform `Promise\u003cT>` into `Promise\u003cT | void>` rather than `Promise\u003cT | undefined>`.\n\n```ts\ndeclare let p: Promise\u003cnumber>;\n// inferred as Promise\u003cnumber | void> while Promise\u003cnumber | undefined> would be SO MUCH NICER here.\nconst q = p.catch((err) => console.log(err));\n```\n\nI propose that all functions with implicit returns should be inferred as returning `undefined` when no return type is provided.\n\nThis behavior should also extend to async and generator functions.\n\nRelated proposal: https://github.com/microsoft/TypeScript/issues/36239\n**EDIT: [This was implemented in TypeScript 5.1](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-1.html)**\n\n### Infer Promise.resolve() as returning Promise\\\u003cundefined\\> and remove any other pressing usages of void in lib.d.ts.\n\nI’m not sure if there are other problematic instances of `void` in TypeScript’s lib typings, but it would be nice if the idiomatic `Promise.resolve()` could just be inferred as `Promise\u003cundefined>`. We could also change callback types to use `unknown` instead of `void` but that change feels much less necessary to avoid `void`.\n\n### Allow trailing parameters which extend undefined to be optional.\n\nOne problem with the semantic changes above which I haven’t mentioned relates to yet another unusual `void` behavior. When trailing parameters in function types extend `void`, they become optional. This kind of makes sense because, for instance, it allows people to omit the argument to the `resolve()` function of a void promise, or the argument to the `return()` method of a void returning generator. Because of this, inferring `undefined` where we used to infer `void` might inadvertently change the required number of arguments to functions, causing type errors where previously there were none.\n\nTherefore, I think if we were to consider the above proposals, we should also strongly consider changing TypeScript to infer trailing parameters which extend `undefined` as being optional.\n\n```ts\nfunction optionalAdd(a: number, b: number | undefined) {\n return b ? a + b : a;\n}\n\n// this should not error\noptionalAdd(1);\n```\n\nThis might be a more controversial change which bogs down the larger project of avoiding void, but I think we could reasonably implement the earlier proposals without making this change. Furthermore, I also think this change would be beneficial to TypeScript in a similar way to making `void` optional. Ultimately, I think the larger theme at play is that TypeScript has too many special ways to indicate undefined-ness which don’t affect the runtime and don’t provide any additional type safety.\n\n___\n\nThese changes might seem sweeping, but the inflexible non-assignability of `void` should make the changes not as hard to upgrade into as they might seem. Moreover, the benefit to the TypeScript ecosystem will be that we can start refactoring `void` out of our type definitions. By replacing `void` with `undefined` and `unknown`, we can start being more explicit about what exactly our functions return and what we want from our callback types without losing type safety.\n\nFurthermore, I think these changes are in line with TypeScript’s design goals, specifically that TypeScript should “3. Impose no runtime overhead on emitted programs” and “4. Emit clean, idiomatic, recognizable JavaScript code.” By allowing `undefined` to model implicit returns and optional trailing parameters, we’re merely describing JavaScript as it is, and the use of `void` to model these values can be surprising.\n\n## ☝️ Potential Objections\nLots of people will object and say that `void` is actually a useful type, that the idea of an opposite “dual” of `any` is interesting or whatever. I don’t care for this kind of astronaut analysis and I don’t think the `void` type is useful, but any such arguments are immaterial to this proposal. My main problem isn’t that the `void` type exists, but that it is forced upon me. To be clear, none of my proposals change the behavior of the `void` type, nor do they seek the removal of the `void` type from TypeScript. I just want `void` to stop being inferred or required when I write idiomatic JavaScript. I believe that even if my proposals were implemented, people who actually cared about `void` could continue to explore the unusual features of this gross type and not know anything had changed.\n\nPeople may also object that they still want to use the `void` type, because its inflexibility is useful for typing callbacks, as a guarantee to callback providers that the return value of the callback is never used. I would argue that for the callback case, `void` is completely superseded by `unknown`, and that you can use `unknown` in the place of `void` when typing first-class functions today without much friction. Furthermore, as the callback provider, if you really wanted to make sure that a callback’s return value is never used, the most idiomatic and foolproof way to do this in JavaScript would be to use the `void` operator in the runtime (`() => void hideMyReturn()`). Ironically, TypeScript infers this function as returning `undefined` and not `void`.\n\n## 🔍 Search Terms\nvoid, undefined, implicit return, non-returning function, noImplicitReturns\n\n## 💣 Relevant Errors\n- TS1345: An expression of type 'void' cannot be tested for truthiness.\n- TS2322: Type 'void' is not assignable to type 'undefined'.\n- TS2355: A function whose declared type is neither 'void' nor 'any' must return a value.\n- TS7030: Not all code paths return a value.\n\n## ✅ Viability Checklist\nMy suggestion meets these guidelines:\n\n* [ ] This wouldn't be a breaking change in existing TypeScript/JavaScript code\n* [x] This wouldn't change the runtime behavior of existing JavaScript code\n* [x] This could be implemented without emitting different JS based on the types of the expressions\n* [x] This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)\n* [x] This feature would agree with the rest of [TypeScript's Design Goals](https://github.com/Microsoft/TypeScript/wiki/TypeScript-Design-Goals).\n\n## 🔗 Selected Relevant Issues\n- https://github.com/microsoft/TypeScript/issues/62\n Earliest reference to the `void` type.\n- https://github.com/microsoft/TypeScript/issues/20006\n Some informative discussions on what maintainers think `void` should do.\n- https://github.com/microsoft/TypeScript/issues/33357\n Void in generator types as it relates to the `return()` method.\n- https://github.com/microsoft/TypeScript/issues/33420\n Documentation of some inconsistencies of function types which return `Promise\u003cvoid>`, indicating that void isn’t as well-baked as some people seem to think it is.\n- https://github.com/microsoft/TypeScript/issues/35850\n Issue which highlights the general confusion surrounding `void`.\n- https://github.com/microsoft/TypeScript/issues/36239\n Proposal to infer non-returning functions as returning `undefined`.\n- https://github.com/microsoft/TypeScript/issues/36288\n Proposal to allow functions whose return type is `undefined` to return nothing.\n- https://github.com/microsoft/TypeScript/pull/40823\n Proposal to make `void` properties optional, which would further entrench `void`.","author":{"url":"https://github.com/brainkim","@type":"Person","name":"brainkim"},"datePublished":"2021-02-09T18:22:42Z","url":"https://github.com/microsoft/TypeScript/issues/42709"}
| 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:6a019726-47de-9379-0a41-03c351070858 |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | A464:1CAE1B:FC856:154072:6B042DA8 |
| html-safe-nonce | 2972e99cca3c1bb384abf2ace781aeda82147b2cb94ac3245f3c348dd5766f59 |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJBNDY0OjFDQUUxQjpGQzg1NjoxNTQwNzI6NkIwNDJEQTgiLCJ2aXNpdG9yX2lkIjoiNzMxNjc0NjAyNDg1MTM1MzAwMCIsInJlZ2lvbl9lZGdlIjoiaWFkIiwicmVnaW9uX3JlbmRlciI6ImlhZCJ9 |
| visitor-hmac | 853cf5e412f548edcdf0ce0e706fbf83f00a451bd5d2e4f7de0aeeef486fbd07 |
| hovercard-subject-tag | issue:804799110 |
| 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/42709/issue_layout |
| twitter:image | https://opengraph.githubassets.com/ccd7f9970514129a6daae1ab621e6bfddd1669b90ed44d923dbb2165ab044002/microsoft/TypeScript/issues/42709 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/ccd7f9970514129a6daae1ab621e6bfddd1669b90ed44d923dbb2165ab044002/microsoft/TypeScript/issues/42709 |
| og:image:alt | Suggestion Allow developers to avoid the void type. I’d like to propose a couple changes to TypeScript to make void an optional type, and infer undefined in more places where void is currently used... |
| og:image:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| og:author:username | brainkim |
| hostname | github.com |
| expected-hostname | github.com |
| None | b7a1d2b9101496921b08579fbee988d014345aef2f5bd660d1f8c7332d81560e |
| 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 | c3dd496c3da6ea6b77e69c09279d2b81604654f1 |
| ui-target | full |
| theme-color | #1e2327 |
| color-scheme | light dark |
| react-app-name | issues |
Links:
| Server | github.com |
| Content-Type | text/html; charset=utf-8 |
| Cache-Control | max-age=0, private, must-revalidate |
Viewport: width=device-width