简体   繁体   English

Typescript在运行时给出错误,但在编译时不给出

[英]Typescript gives error during runtime but not on compile time

I am trying to learn Typescript, and can't seem to find the issue with my code, i tried searching but couldn't find any relevant material related to my issue. 我正在尝试学习Typescript,但似乎找不到与我的代码相关的问题,我尝试搜索但找不到与我的问题相关的任何相关材料。 Here's my code:- 这是我的代码:-

<code>
class Hello{
    lars: string;

    constructor(name: string) {
        this.lars = name;
    }

    sayHello(){
        return `hello ${this.lars}`;
    }
}

let b = new Hello('Metallica');
</code>

i compile the code using the tsc test.ts, it compiles with no errors, but when i run it using node test.ts, it gives me following error: 我使用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>

The file runs when i user Node test.js, but don't get the expected output ie "Hello Metallica", while node test.ts fails. 当我使用Node test.js时,该文件运行,但是没有获得预期的输出,即“ Hello Metallica”,而node test.ts失败。

Here's the compiled code:- 这是编译后的代码:

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');

There's nothing wrong with the typescript. 打字稿没有错。 You're not seeing the expected result because: 您没有看到预期的结果,因为:

  1. You can't run the typescript. 您无法运行打字稿。 Typescript should be compiled to javascript, which then can be run by for example node. Typescript应该编译为javascript,然后可以由例如node运行。 You should run node test.js 您应该运行node test.js
  2. There is no line which logs to the console. 没有行记录到控制台。 Try changing the last line to console.log(new Hello('Metallica').sayHello()); 尝试将最后一行更改为console.log(new Hello('Metallica').sayHello()); for example. 例如。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM