[英]Typescript gives error during runtime but not on compile time
我正在嘗試學習Typescript,但似乎找不到與我的代碼相關的問題,我嘗試搜索但找不到與我的問題相關的任何相關材料。 這是我的代碼:-
<code>
class Hello{
lars: string;
constructor(name: string) {
this.lars = name;
}
sayHello(){
return `hello ${this.lars}`;
}
}
let b = new Hello('Metallica');
</code>
我使用tsc test.ts編譯代碼,它編譯沒有錯誤,但是當我使用節點test.ts運行它時,它給了我以下錯誤:
<blockquote>
lars: string;
^
SyntaxError: Unexpected token :
at createScript (vm.js:80:10)
at Object.runInThisContext (vm.js:139:10)
at Module._compile (module.js:616:28)
at Object.Module._extensions..js (module.js:663:10)
at Module.load (module.js:565:32)
at tryModuleLoad (module.js:505:12)
at Function.Module._load (module.js:497:3)
at Function.Module.runMain (module.js:693:10)
at startup (bootstrap_node.js:188:16)
at bootstrap_node.js:609:3
</blockquote>
當我使用Node test.js時,該文件運行,但是沒有獲得預期的輸出,即“ Hello Metallica”,而node test.ts失敗。
這是編譯后的代碼:
var Hello = /** @class */ (function () {
function Hello(name) {
this.lars = name;
}
Hello.prototype.sayHello = function () {
return "hello " + this.lars;
};
return Hello;
}());
var b = new Hello('Metallica');
打字稿沒有錯。 您沒有看到預期的結果,因為:
node test.js
console.log(new Hello('Metallica').sayHello());
例如。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.