简体   繁体   English

Typescript声明顺序触发运行时错误

[英]Typescript declaration order triggers runtime error

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. 在搜索我遇到的问题时,我发现声称类的声明顺序在Typescript中无关紧要 ,并且“前向声明”不是必需的。

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. 要么我错过了一个我不知道的关键词,要么“声明顺序不重要”并不像人们想象的那样通用。

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. 对于继承,B必须在A之前定义,以便A可以从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 此外,“声明”(订单从不重要)和“定义”之间存在区别,其中订单几乎总是重要的,除了吊装http://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html等案例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM