'Is field initialization by another field permitted?

I'm trying to do this in my class:

class Foo {
    _errorHappened = new Subject();
    errorHappened = this._errorHappened.asObservable();
}

I'm using a field's value during inline initialization of another field. The provided example works, and if I flip the order of those two lines, it throws Cannot read property 'asObservable' of undefined error. This makes me think that parser processes class declaration top-down, and all is good if you reference field that is already defined above.

My question is: can this behavior be trusted? I mean, is this a documented behavior, or it "just works" right now but is not guaranteed to not break in future? In some other languages such initialization is not possible (you have to use constructor). Is this just OK in TypeScript? Can you link to relevant section in docs?



Solution 1:[1]

Yes, you can trust that behavior.

TypeScript's ethos is (roughly) to be JavaScript with types, but aggressively adopting new features that are in the JavaScript pipeline into the TypeScript compiler where feasible and prudent. So the question becomes: In the JavaScript proposal for public class fields (which is part of the specification now), can a field use a previous field's value in its initializer? The answer is yes. The instance (e.g., non-static) class field initializers are run after this is established (which is important, it means we can use this) and they're run in order. Details in the specification.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1