Isolated declarations should infer void
and Promise<void>
for methods without return statementsΒ #60993
Description
π Search Terms
isolated declaration
isolated declarations
void
Promise
infer return type
β Viability Checklist
- This wouldn't be a breaking change in existing TypeScript/JavaScript code
- This wouldn't change the runtime behavior of existing JavaScript code
- This could be implemented without emitting different JS based on the types of the expressions
- This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
- This isn't a request to add a new utility type: https://github.com/microsoft/TypeScript/wiki/No-New-Utility-Types
- This feature would agree with the rest of our Design Goals: https://github.com/Microsoft/TypeScript/wiki/TypeScript-Design-Goals
β Suggestion
TypeScript infers a return type of void
for a sync function with no return statements, and a type of Promise<void>
for an async function with no return statements.
This behavior is compatible within the constraints of isolated declarations since it's knowable just from the local AST. This behavior is similar to inferring a return type of number
for a function that's just return 10;
as isolated declarations does today.
Simple playground example of code that fails with IsolatedDeclarations today, that I'm proposing be allowed: playground link
π Motivating Example
Functions without return statements have an inferred type of void
(or Promise<void>
if async). To reduce the amount of friction for adopting and using --isolatedDeclarations
, TypeScript will no longer require an explicit type annotation in cases like these when --isolatedDeclarations
is enabled:
export function clickHeader() {
document.querySelector('h1')?.click();
}
export async function loadContent() {
await import('./extra-content.js');
}
π» Use Cases
- What do you want to use this for?
In adopting isolated declarations in Google's internal codebase, we've found some modules make frequent use of void functions. This will reduce the friction to adopting --isolatedDeclarations
and in writing and maintaining code using it.
- What shortcomings exist with current approaches? What workarounds are you using?
We add explicit return types in these cases. Not the worst thing in the world, but nice to reduce friction for trivial cases like this.