Description
Suggestion
I think it would be useful to have an option to forbid the assignment of void
values to variables/parameters of type any
.
π Search Terms
flag assign why is void assignable to any
β Viability Checklist
My suggestion meets these guidelines:
- 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 feature would agree with the rest of TypeScript's Design Goals.
β Suggestion
My suggestion is to add a flag to disallow assignment of void
values to variables/parameters of type any
.
As I understand it, writing void
as a return value means that the value will not be observed. Assigning the value to a variable of type any
thus seems like an undesirable action, and I wonder why this is even allowed at all.
π Motivating Example
Simple example
Current behavior:
const x: () => void = () => 42; // So far so good
console.log(x()); // Prints 42; this shouldn't be allowed because `x` returns void
Desired behavior if suggestion is implemented and flag is active:
const x: () => void = () => 42;
console.log(x()); // Error: void is not assignable to any
More involved example
const thanks = document.createElement("span");
thanks.textContent = "Thanks for supporting us!";
thanks.hidden = true;
const showThanksMessage: () => void = () => thanks.hidden = false;
const support = document.createElement("a");
support.textContent = "Support us!";
support.href = "/donate";
support.target = "_blank";
support.onclick = showThanksMessage;
document.body.append(support, " ", thanks);
Notice that when you click the support link, the donation page does not actually open. This is because showThanksMessage
, which has a void
return type, secretly returns false
. This is then assigned to the onclick
callback, which is a function returning any
. This is then interpreted by the browser as 'prevent the default action of opening the link' (nowadays most people would use Event#preventDefault()
to do this).
With the proposed flag enabled, the assignment to onclick
would be an error, as we would not be able to assign () => void
to (ev: MouseEvent) => any
because of the return types.
π» Use Cases
This prevents people from accidentally using the values of void
-returning functions, as demonstrated above.