4

I am messing with the Typescript playground, and the only differences I'm finding between void and undefined are as follows:

  • I can assign an undefined value to a void-type variable, but I can't do the opposite.

  • A function whose return type is explicitly stated to be one (and only one) of these two types will trigger errors or fail to trigger errors in accordance with the rule stated above - except when there is no return statement at all, in which case the void return value type is still acceptable, while the undefined return value type is not.

I don't know of any other differences. Are there any other differences? It appears to me that, as long as the relevant strict-mode compilation flags are on, the type undefined encompasses exactly one value - the JavaScript value undefined - while the type void encompasses exactly two conceptual values: the JavaScript value undefined, and the variant of the JavaScript value undefined that arises when a function returns by reaching its end rather than by reaching a return statement or by throwing. (And of course, these two variants of the value undefined are exactly the same thing as far as ordinary JavaScript is concerned.)

Am I missing anything?

(I guess that if some option is changed then null will also get involved here, but I'm not as interested in that, personally, so I haven't looked into it.)

mjwach
  • 1,174
  • 2
  • 9
  • 25
  • 1
    `void` in TypeScript is *weird*. The only value you can directly assign to a `void` variable is `undefined` or another `void` value. But a variable of type `()=>void` can accept any zero-arg function that returns anything. The `void` return type is supposed to mean "don't try to use the return value" and not "this is definitely `undefined`". And a trailing function parameter of type `void` can be omitted. And probably other weird stuff. I wonder if there's another answer out there somewhere that explains it so I don't have to write out all the weird things about `void`. – jcalz Oct 15 '20 at 20:41
  • 2
    Possible duplicate of [Why does TypeScript have both `void` and `undefined`?](https://stackoverflow.com/questions/58885485/why-does-typescript-have-both-void-and-undefined) – jcalz Oct 15 '20 at 20:43
  • That question effectively asks for ONE or more existence-justifying differences and a explanation of why this distinction between types was thought useful, whereas I am asking for ALL (ideally) mechanical differences and NOT for any justification of the language's design. The questions are different. (It seems that this "unused return value" concept is a big difference that I missed, though! So that is certainly relevant.) – mjwach Oct 15 '20 at 21:26

0 Answers0