Peter
Peter

Reputation: 505

Order of class definitions - any way to circumvent?

I am discovering that TypeScript does not give an error when I try to create a new instance of class B inside of class A.

class A {
    public static foo = new B();
}

class B { }

Calling A.foo after these definitions would obviously fail since B is not lexically before A. Removing static is not an option (because I do not want to).

So, is my only option to do the reordering of the class definitions manually, or are there any tricks I can do to circumvent this? Would a module loader help me here, or do I still need to explicitly define the depencency order?

Upvotes: 1

Views: 1010

Answers (1)

TSV
TSV

Reputation: 7641

Your Typescript code

class A {
    public static foo = new B();
}

class B { }

transpiles into following JavaScript:

var A = (function () {
    function A() {
    }
    A.foo = new B();
    return A;
}());
var B = (function () {
    function B() {
    }
    return B;
}());

JavaScript processes file consequently, and at the line

    A.foo = new B();

"B" is undefined, because is not parsed by JS yet.

This can be solved via:

1) Reordering class declarations in the file

2) Extracting "B" class code into a separate file and referencing in in A file with

2.1) /// <reference path="B.ts" />

this should be added in the top of A.ts file, this will explicitly define the dependency order

2.2) or using require (import) directive and modular building

Update 1

Variant 2.1:

a.ts

/// <reference path="b.ts" />
class A {
    public static foo = new B();
}

b.ts

export class B { }

Variant 2.2 (i've not tested exactly this code, but think it works):

a.ts

import { B } from "./b";

class A {
    public static foo = new B();
}

export { A };

b.ts

class B { }

export { B };

Upvotes: 3

Related Questions