Typescript: Infer non returning function to be returning `undefined`, not `void`

Created on 16 Jan 2020  ·  12Comments  ·  Source: microsoft/TypeScript

Search Terms

non returning, undefined instead of void, undefined or unknown instead of void

Suggestion

  • Change return of non returning functions to undefined instead of void
  • Accept unknown as a type of non returning functions
    examples:
const f = () => {} // this gets inferred as () => void

const f1 = (): undefined => {} // doesn't work
// error: A function whose declared type is neither 'void' nor 'any' must return a value.(2355)

const f2 = (): unknown => {} // same error

https://www.typescriptlang.org/play/#code/MYewdgzgLgBAZjAvDAFASiQPhgbwL4CwAUMaJLHAIxKpoBcMArmACYCmcAlmGy1rjEIkiZaPABMNdA2YBrMCADuYfvmJA

Motivations

void is an annoying type to deal with, has many inconsistencies and there's a ton of issues around it for its weird behavior like: #35850 , #35236 , #33420 ... etc
Non-returning functions actually return undefined which is a more predictable type to deal with and narrow disjunctions with and even use optional chaining with.

Use Cases

Many use cases appear while using promises where there's a need to catch an error but at the same time not deal with void

const f = () => {}
async (p: Promise<A>) => {
  const a = await p.catch(f);
  // do stuff with a whose type is now A | void
};

Checklist

My suggestion meets these guidelines:

  • [ ] This wouldn't be a breaking change in existing TypeScript/JavaScript code

Not sure if this might break some code or not but I think any code that dealt with void should work while dealing with undefined?

  • [x] This wouldn't change the runtime behavior of existing JavaScript code
  • [x] This could be implemented without emitting different JS based on the types of the expressions
  • [x] This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, etc.)
  • [x] This feature would agree with the rest of TypeScript's Design Goals.
In Discussion Suggestion

Most helpful comment

Let's say today you write a function and there's no useful value to return.

Then, next month, you decide that it'd be better if the function returned a number of some kind.

Is this a breaking change in your API contract?

If the non-returning version of the function was marked as void, then no, it can't be a breaking change, because the rules around void effectively prevent a consumer from depending on the return value.

If the non-returning version of the function was marked as undefined, then yes, it absolutely can be a breaking change. Code like this

const p = fn() || 2;

would have been an error under void, but is OK under : undefined and now changes behavior. There is substantial risk of downstream code changing behavior when a function goes from returning "nothing" to returning "something"; having the "nothing" case be void mitigates that risk.

What are we getting in return? The "confusion" around void is generally around people not understanding what it means to mark a function's return value as unspecified, which is its primary source of future-safety.

All 12 comments

I like the current behavior. If I write a function with no return <expr> in it at any point, then there's no reason for me to try to observe the return value of it, and any attempt to observe the return value is probably a mistake. I like it when Typescript catches my mistakes.

undefined is a more specialized and narrower type that void
My guess is if a function always returns undefined there's no reason to observe its return type either.

Another case is if you are using a function of type () => void in the catch part of a promise, you'll end up with a type like this: Promise<A | void>, at this point you care to know that your catch isn't actually returning A which will be hard to handle

I hate the following error. The compiler requires a return statement although I just intend to reject null.

declare function f<T>(g: () => T): void;
f<undefined>(() => { }); // error

Let's say today you write a function and there's no useful value to return.

Then, next month, you decide that it'd be better if the function returned a number of some kind.

Is this a breaking change in your API contract?

If the non-returning version of the function was marked as void, then no, it can't be a breaking change, because the rules around void effectively prevent a consumer from depending on the return value.

If the non-returning version of the function was marked as undefined, then yes, it absolutely can be a breaking change. Code like this

const p = fn() || 2;

would have been an error under void, but is OK under : undefined and now changes behavior. There is substantial risk of downstream code changing behavior when a function goes from returning "nothing" to returning "something"; having the "nothing" case be void mitigates that risk.

What are we getting in return? The "confusion" around void is generally around people not understanding what it means to mark a function's return value as unspecified, which is its primary source of future-safety.

I disagree, for me, specified types/behavior trumps unspecified types/behavior. and I think that contradicts with your comments before that specified behavior should be annotated as so. Non-returning functions have a specified behavior too.
https://github.com/microsoft/TypeScript/issues/35236#issuecomment-559280058

Oh, and that console.error and its friends should have their return types changed from void to undefined since that behavior is specified

Anyway, if you plan not to accept this issue, is it possible to accept an new issue to allow this?

function a(): undefined { }
function b(): unknown { }

I think those are pretty reasonable, at least with noImplicitReturns off

@RyanCavanaugh https://github.com/microsoft/TypeScript/issues/36239#issuecomment-575722576 is not the issue here. I mean the compiler can know that the return type can be undefined from the function body. This is an issue of type inferences rather than type checking.

If the non-returning version of the function was marked as undefined by the type of the receiver, probably it can't be a breaking change.

So I disagree with author's use case but the compiler should allow non-returning functions to return the undefined type in some cases.

I separated the issues into #36288 because declaring undefined return type with no context is not my main intent here.

EDIT: it looks like #36288 might be a better place for me to raise the below case? Not really sure, as both issues seem relevant.


I'm running into a situation where I have a func(): Promise<void | Result> which can possibly return a value, but not necessarily so.

At the call site, I'm trying to do:

const res = await func();

if (res?.field) {
   ...
}

however the compiler flags this an error, as optional chaining doesn't work on void types (assuming this is intended behavior?). Oddly, it does work if I instead do:

const res = await func();

if (res && res.field) {
   ...
}

This seems weird to me, since I expect res?.field to be equivalent to / interchangeable with res && res.field.

The only thing I can think to do, besides using the res && res.field condition, is changing the function to instead return Promise<undefined | Result>, however I dislike this approach because it requires that the function explicitly return undefined, which I consider to be unnecessary.

This would be very useful.

Imagine a function a bit like found in immer where the return type is void, and an object is passed for the sole purpose of being mutated (it's actually a proxy that doesn't get mutated but that's how the api looks like from the outside)

so you expect people to write something like:

update(obj, draft => {
  draft.name = 'the new name'
})

If one doesn't pay attention, it's very easy to return a transformed object and expect this change to be picked up. It won't do anything and there is no compilation error:

update(obj, draft => newObjFromApi) // Oh no, this won't do anything.

This is not a fiction by the way, this happened 5 minutes ago 😆
The type system could really help us detect these usage mistakes.

EDIT: Nevermind, it seems () => void | undefined already does exactly that. Is there any drawback?

Was this page helpful?
0 / 5 - 0 ratings

Related issues

weswigham picture weswigham  ·  3Comments

siddjain picture siddjain  ·  3Comments

fwanicka picture fwanicka  ·  3Comments

bgrieder picture bgrieder  ·  3Comments

kyasbal-1994 picture kyasbal-1994  ·  3Comments