Reputation: 11268
Searching for a problem I have, I found claims that the declaration order of classes doesn't matter in Typescript, and that 'forward declarations' are not necessary.
In a project I am reviewing right now, this claim doesn't seem to hold up. I broke the issue down into a simple reproducible example, where even though the compiler doesn't complain, we fail at runtime:
$ cat bug.ts
class A extends B {
constructor(public id:number) {
super(id);
console.log("A():" + id);
}
}
class B {
constructor(public id:number) {
console.log("B():" + id);
}
}
var a = new A(12);
$ tsc bug.ts
$ node bug.js
/home/ttsiod/work/a/bug.js:4
__.prototype = b.prototype;
^
TypeError: Cannot read property 'prototype' of undefined
at __extends (/home/ttsiod/work/a/bug.js:4:21)
at /home/ttsiod/work/a/bug.js:8:5
at Object.<anonymous> (/home/ttsiod/work/a/bug.js:15:3)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:901:3
Either I am missing a keyword I don't know about, or the claim of "declaration order is not important" is not as generic as one would think.
Upvotes: 4
Views: 1296
Reputation: 276363
I matters for inheritance. It doesn't matter as long as it is defined before it is used, which is the case in the link you mentioned.
For inheritance B must be defined before A, so that A can copy over members from the prototype of B.
Also there is a distinction between "declaration" (where order never matters) and "definition" where order almost always matters except for cases like hoisting http://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html
Upvotes: 3