[英]Why Typescript adds .default() to class constructor in transpiled code?
[英]Typescript class.default is not a constructor
創建一個Angular2應用程序時,我在第一個類的構造函數中調用另一個類的構造函數時遇到以下問題。
頭等艙代碼
import SecondClass from './second-class'
export class FirstClass {
someVar:string;
secondClass:SecondClass;
constructor(firstClass?: FirstClass) {
someVar='test';
secondClass= new SecondClass;
}
}
二等代碼:
export class SecondClass {
someOtherVar:string;
constructor(secondClass?:SecondClass) {
someOtherVar='test';
}
}
會給我錯誤:ORIGINAL EXCEPTION:TypeError:second_class_1.default不是構造函數
內容為./second-class
System.register([], function(exports_1, context_1) {
"use strict";
var __moduleName = context_1 && context_1.id;
var SecondClass;
return {
setters:[],
execute: function() {
SecondClass = (function () {
function SecondClass(secondClass) {
this.someOtherVar='test';
}
return SecondClass;
}());
exports_1("SecondClass", SecondClass);
}
}
});
//# sourceMappingURL=second-class.js.map
這是Typescript編譯器的編譯輸出
錯誤消息表示您在./second-class
(非默認值)中使用了命名導出( export class SecondClass {}
)。 所以這意味着你的導入看起來應該是這樣的
import {SecondClass} from './second-class'
代碼中存在一些錯誤:
從導入中丟失{}
missing ()
從調用構造函數
從訪問類成員中錯過了this
頭等艙代碼
import {SecondClass} from './second-class'
export class FirstClass {
someVar:string;
secondClass:SecondClass;
constructor(firstClass?: FirstClass) {
this.someVar='test';
this.secondClass= new SecondClass();
}
}
二等代碼:
export class SecondClass {
someOtherVar:string;
constructor(secondClass?:SecondClass) {
this.someOtherVar='test';
}
}
這太晚了,但我現在也遇到了同樣的錯誤。 解決方案是默認導出SecondClass
,因此Second Class代碼將是:
export default class SecondClass {
someOtherVar:string;
constructor(secondClass?:SecondClass) {
this.someOtherVar='test';
}
}
並import SecondClass from './second-class'
導入其他類中的import SecondClass from './second-class'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.