Typescript在运行时出错,但不是在编译时出错
我正在尝试学习Typescript,但似乎找不到代码的问题,我尝试了搜索,但找不到任何与我的问题相关的材料。 这是我的密码:-Typescript在运行时出错,但不是在编译时出错,typescript,Typescript,我正在尝试学习Typescript,但似乎找不到代码的问题,我尝试了搜索,但找不到任何与我的问题相关的材料。 这是我的密码:- <code> class Hello{ lars: string; constructor(name: string) { this.lars = name; } sayHello(){ return `hello ${this.lars}`; } } let b = new He
<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编译代码,它编译时没有错误,但当我使用node 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
console.log(newhello('Metallica').sayHello())代码>例如
听起来它根本没有被编译,或者,你可能没有运行编译后的脚本。我使用的是VS代码,我确信它编译正确,console.log('here');当我运行test.js文件时,出现在控制台中,但是运行test.tsc时出错。您可以发布编译后的代码吗?
var Hello=/**@class*/(函数(){function Hello(name){this.lars=name;}Hello.prototype.sayHello=function(){return Hello+this.lars;};return Hello;});var b=新Hello('Metallica')代码>谢谢,完全错过了。its给出错误的意外标记“:”的原因是什么?我是否声明的类型不正确?不,声明是正确的。您只会在尝试运行.ts文件时看到该错误。我尝试了console.log(new Hello('Metallica)),它返回了对象“Hello{lars:Metallica},并且我尝试将我的方法sayHello()更改为return console.log('here'),但它没有返回任何内容。我编辑了答案。它应该是console.log(new Hello('Metallica')).sayHello())
对不起,我的错误,让它工作了,谢谢,我在org的typscriptlang上学习教程,没有调用sayHello()方法
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');