sierraw5
sierraw5

Reputation: 21

Class definition order

Can someone explain why the following typescript code compiles? It seems to me that it could never successfully run.

class Xyz
    {
    static x : Abc = new Abc();
    }

class Abc
    {

    }

Upvotes: 2

Views: 484

Answers (2)

Ryan Cavanaugh
Ryan Cavanaugh

Reputation: 221044

TypeScript doesn't do any enforcement of ordering of constructs in your code. Consider some slight variant that would be valid -- it's not immediately obvious what things should be allowed or disallowed in terms of ordering.

class Xyz
    {
    static x = () => new Abc();
    }

class Abc
    {

    }

There's an issue tracking adding this as an option for the straightforward cases.

Upvotes: 1

Peter Olson
Peter Olson

Reputation: 142939

There is no compile-time error, since it is equivalent to this syntactically valid JavaScript

var Xyz = (function () {
    function Xyz() {
    }
    Xyz.x = new Abc();
    return Xyz;
})();
var Abc = (function () {
    function Abc() {
    }
    return Abc;
})();

but it will have a runtime error since you try to instantiate a member of Abc before Abc is defined.

Upvotes: 1

Related Questions