0

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.

3
  • ... who says it can't? Commented Jan 20, 2018 at 16:18
  • 1
    Related (different SE site, but worth a read anyway) Commented Jan 20, 2018 at 16:19
  • @user202729 Ok if so, why it does? Commented Jan 20, 2018 at 16:19

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.