[英]Type Declaration Order in TypeScript
TypeScript对类型声明的顺序敏感吗?
更改类型的顺序会导致Angular 2(beta.0)内部发生错误,该错误(AFAIK)是使用TypeScript本身实现的(这就是为什么此错误对我而言如此奇怪且无关紧要):
angular2-polyfills.js:138 Error: Cannot read property 'prototype' of undefined(…)
假设我们有一个文件t1.ts
:
export class AuthResponse extends JsonResponse { }
export class JsonResponse {
public code: ResultCode;
}
export enum ResultCode { }
启动应用程序时,我们会在客户端看到提到的错误。 但是,如果我们颠倒该文件中声明的顺序,该错误就会消失(仅作记录,目前我正在前进,请牢记这一点并且它可以正常工作)。
要重现此错误,我们还需要五个文件:
t2.ts
:
import {AuthResponse, JsonResponse, ResultCode} from './t1'; // this order?
export class DummyAction {
doSomething() {
console.log('test, starting ...');
var v = new AuthResponse();
return v;
}
}
app.component.ts
:
import {Component, OnInit} from 'angular2/core';
import {DummyAction} from './components/t2';
@Component({
selector: 'root-app',
templateUrl: '/app/templates/app.html',
})
export class AppComponent implements OnInit {
constructor() {
var tester = new DummyAction();
// tester.runTest();
}
ngOnInit() { }
}
app.html
:
<h1>TEST</h1>
boot.ts
:
import {bootstrap} from 'angular2/platform/browser';
import {AppComponent} from './app.component';
bootstrap(AppComponent, []);
而index.html
稍大一些,但本质上具有angular网站上教程中的index.html
结构。
TypeScript本身并不敏感,但是可以编译为JS。
class A extends B {}
class B {}
在JS中:
var A = (function (_super) { /* ... */ })(B);
var B = (function () { /* ... */ })();
B在第1行中未定义。
我已对vasa_c答案投了赞成票,因为它是正确的答案。 下面,我想提供有关此问题的更多信息,以便OP可以更轻松地理解该问题。
如果我们采用您的示例代码:
export class AuthResponse extends JsonResponse { }
export class JsonResponse {
public code: ResultCode;
}
export enum ResultCode { }
编译它-最终结果将是这样:
var AuthResponse = (function (_super) {
__extends(AuthResponse, _super);
function AuthResponse() {
_super.apply(this, arguments);
}
return AuthResponse;
})(JsonResponse);
exports.AuthResponse = AuthResponse;
var JsonResponse = (function () {
function JsonResponse() {
}
return JsonResponse;
})();
exports.JsonResponse = JsonResponse;
(function (ResultCode) {
})(exports.ResultCode || (exports.ResultCode = {}));
var ResultCode = exports.ResultCode;
请注意,生成的代码不仅仅是函数定义。 它是函数和变量。 一切都与众不同。 因为您同时具有声明和表达式。 有关此问题的更多信息以及为什么以js顺序表达表达式很重要,您可以在此出色的文章中阅读: JavaScript函数声明和评估顺序
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.