I encountered a strange behavior that is puzzling to me, and I'm not sure if there's a logical explanation for it.
In TypeScript, the following code works perfectly:
type UndefinedFunction = () => undefined;
let uf: UndefinedFunction = function() {
return; // no errors
}
This makes sense to me because in JavaScript, when a function uses return;
without a value, the returned value is undefined
.
However, the following code results in an error:
type MaybeUndefinedFunction = () => string | undefined;
let muf: MaybeUndefinedFunction = function() {
return; // error
}
An error message is displayed stating that
Type '() => void' is not assignable to type 'maybeUndefinedFunction'. Type 'void' is not assignable to type 'string | undefined'
This inconsistency confuses me. Although I found information regarding void vs undefined on Stack Overflow, it doesn't explain why return;
is now identified as void
instead of
undefined</code, especially when it worked fine in the previous example.</p>
<p>To resolve the error, I can use <code>return undefined;
, but I am curious about why this workaround is necessary since both return;
and return undefined;
should have the same outcome.
Interestingly, the same issue occurs when not returning anything at all - it works in the first case but produces an error in the second, despite both complying with the expected undefined
return value.
If you'd like to see the error in action, check out this playground link: Playground Link