简体   繁体   中英

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. 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:

<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.

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. You should run 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()); for example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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