ecmascript 6 - Typescript ข้อผิดพลาด "class ไม่ใช่ตัวสร้าง"
ฉันกำลังรันโค้ด TypeScript ต่อไปนี้ในสภาพแวดล้อมเป้าหมาย ES6 และมันบอกว่า "Cars ไม่ใช่ตัวสร้าง"
ฉันได้ติดตามลิงก์และลองเปลี่ยนสภาพแวดล้อมเป้าหมายเป็น ES5 แล้ว มันทำงานได้ดี มีใครสามารถบอกได้ไหมว่าทำไมมันถึงไม่ทำงานสำหรับเป้าหมาย ES6
นี่คือโค้ด TypeScript ของฉัน:
export class Cars {
constructor(public len: number,public wid: number) { }
}
export function getSize(): Cars {
return new Cars(20, 30);
};
ข้อผิดพลาดคือ "Cars is not a constructor" ในฟังก์ชัน getSize
อ้อ ฉันกำลังพยายามโหลดไฟล์ทั้งหมดด้วย Systemjs
อย่างไรก็ตาม ฉันกำลังได้รับข้อผิดพลาดในเบราว์เซอร์........ ไม่ใช่ขณะคอมไพล์มัน...
นี่คือโค้ดที่คอมไพล์แล้วของไทป์สคริปต์ด้านบน....
System.register([], function(exports_1, context_1) {
"use strict";
var __moduleName = context_1 && context_1.id;
var Cars;
function getSize() {
return new Cars(20, 30);
}
exports_1("getSize", getSize);
return {
setters:[],
execute: function() {
class Cars {
constructor(len, wid) {
this.len = len;
this.wid = wid;
}
}
;
exports_1("Cars", Cars);
}
}
});
//# sourceMappingURL=Cars.js.map
คำตอบ #1
ตรวจสอบให้แน่ใจว่าคุณไม่มีไฟล์ .js และ .ts อยู่ในไดเรกทอรีเดียวกัน สิ่งนี้อาจเกิดจาก IDE ของคุณในบางครั้ง
คำตอบ #2
(กำลังคัดลอกโพสต์ของฉันจากปัญหา GH ที่คุณเปิดไว้)
นี่คือข้อบกพร่องใน TS 1.8.10 และได้รับการแก้ไขใน master
tsc -t es6 ./foo.ts -m systemใน 1.8.10 ให้:
System.register([], function(exports_1, context_1) {
"use strict";
var __moduleName = context_1 && context_1.id;
var Cars;
function getSize() {
return new Cars(20, 30);
}
exports_1("getSize", getSize);
return {
setters:[],
execute: function() {
class Cars { // (1)
constructor(len, wid) {
this.len = len;
this.wid = wid;
}
}
exports_1("Cars", Cars);
}
}
});
ดังนั้น getSize จึงลงเอยด้วยการใช้ var Cars ซึ่งเป็น undefined.
ใน master ผลลัพธ์สำหรับ (1) กลายเป็น Cars=class Cars { ดังนั้นมันจึงกำหนดให้กับ var Cars และ getSize() ทำงานได้
