簡體   English   中英

TypeScript中的類型聲明順序

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM