-
Notifications
You must be signed in to change notification settings - Fork 12.5k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Narrow const variables in function declarations #8976
Comments
Declared functions are hoisted so we can't actually be certain the initialization has occurred. |
True, but it is likely to run into a runtime error if the hoisted function is called: cb();
const x = [];
function cb() {
x.push(1); // Uncaught ReferenceError: x is not defined
} In theory, static analysis could have flagged the issue, but I can't see any additional problems it would introduce. |
Also cb(); // TypeError: cb is not a function
const x = [];
var cb = function() {
x.push(1);
} |
@kitsonk No, My point about hoisting is this: Since a hoisted function is defined (i.e. non-undefined) before any code executes in a particular file, it doesn't make sense to consider where in the control flow a function is declared. The behavior should be the same no matter where in a file a function declaration is placed. Part of the problem here is that we're debating a fairly meaningless example: const x: number | number[] = []; // Why this annotation when x can't be reassigned?
function cb() {
x.push(1); // Error
} Here's something more meaningful: const x: number[] = [];
function cb() {
x.push(1); // Ok
} Since In the example with a function expression const x: number | number[] = [];
var cb = function() {
x.push(1); // Ok
} we know from control flow analysis that |
Not to argue (especially with you), but that is why I linked to the Playground. Because it is a But I understand the rest of your point in that because |
Ah, sorry for the confusion. What I meant was that the initialization of |
one thing to note, with closing this we chose to ignore the cases of block scoped function declarations (i.e. ES6 in strict mode function declarations): "use strict";
let x: number | number[];
if (isArray(x)) {
function foo() {
x.push(1) // Error
}
} |
With #8849, control flow analysis happens thorough function expression and lambda boundaries for const variables.
it should also be applied to function declarations, class expressions, and class declarations, etc..
so today this works:
but not this:
The text was updated successfully, but these errors were encountered: