riki
riki

Reputation: 2393

Typescript compiler generates javascript even after compilation error

I am new to TypeScript and trying few basic stuffs. So I compile below app1.ts code

class Monster {
    constructor(name, initialPosition) {
        this.name = name;
        this.initialPosition = initialPosition; 
    }
}

I believe we can add any properties to class Monster on fly like we can do in JS. So this.name and this.initialPosition should be a valid way. But as soon as I compile the code it has thrown below errors

app1.ts(3,14): error TS2339: Property 'name' does not exist on type 'Monster'.

app1.ts(4,14): error TS2339: Property 'initialPosition' does not exist on type ' Monster'.

At this moment I thought we probably cannot add properties on fly (well, I got to know that we cannot do it like ECMA 6, we have to define properties - that's good) but when I check the generated JS it really surprised me. After compilation error it generated below JS code

var Monster = /** @class */ (function () {
    function Monster(name, initialPosition) {
        this.name = name;
        this.initialPosition = initialPosition;
    }
    return Monster;
}());

I am a bit confuse. Why after compilation error it generated JS? What actually going on.

Upvotes: 0

Views: 37

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249466

There are some types of errors relate to type checking that allow the compiler to emit JS. Just because the typescript compiler can't prove the program is typesafe does not mean it will not run. If the code can run it will be outputted to JS (so type errors allow emit, but syntactic ones do not)

There is a compiler option controlling this --noEmitOnError. You can read more here

Upvotes: 1

Related Questions