Class properties referencing the class get incorrect class value when using functions defined outside the class
See original GitHub issueTypeScript Version: 2.8.3
(also attempted with typescript@next
at 2018-04-21 23:13:22 UTC)
Search Terms:
- “class properties”
- “class props”
- “class prop”
- the title of this issue
Code
function f() {
return new A();
}
class A {
static x = f();
}
console.log(A.x);
Expected behavior:
The function f
should be able to access the correct value of A
(a function), not undefined
, when called inside a class property initializer.
It should work the same way as this code:
function f() {
return new A();
}
class A {
static x;
}
A.x = f();
console.log(A.x);
Actual behavior:
The class property initializer call to f()
sees the value of A
as undefined
because A
is assigned to the result of an IIFE which has not completed yet:
function f() {
return new A();
}
var A = /** @class */ (function () {
function A() {
}
A.x = f();
return A;
}());
console.log(A.x);
Compare with the Babel output for this code which is:
"use strict";
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function f() {
return new A();
}
var A = function A() {
_classCallCheck(this, A);
};
A.x = f();
console.log(A.x);
And references the correct value of A
when f()
is called.
Playground Link: https://www.typescriptlang.org/play/#src=function f() { return new A()%3B } class A { static x %3D f()%3B } console.log(A.x)%3B
Related Issues:
Closest issues I could find were still not terribly related:
Issue Analytics
- State:
- Created 5 years ago
- Comments:5 (3 by maintainers)
Top GitHub Comments
Our emit is correct for
--target es6
and later. the emit for--target es5
is not correct, since the class is not bound until all static initializers are run. this is does not match the TC39 proposal.For context we have changed the way classes re emitted in ES5 to support for better minification, undoing that would impact the minification scenario.
Gotcha. Thanks for the explanation.
On Tue, May 1, 2018, 18:25 Ron Buckton notifications@github.com wrote: