Why does the a default Attribute translates to nothing instead of undefined?

Viewed 29

If I have a class with an attribute in Typescript, it will create a class without the attribute in Javascript. This is also the behaviour for interfaces.

The following Typescript:

class Foo{
    bar : string;
}

let x = new Foo();
console.log("bar" in x); // results in false

Will result in following JS (target es6):

class Foo {
}
let x = new Foo();
console.log("bar" in x);

I would expect an attribute that has the default value of undefined like this:

class Foo{
    bar : string = undefined;
}

let x = new Foo();
console.log("bar" in x); // returns true

that will translate in the expected code:

class Foo {
    constructor() {
        this.bar = undefined;
    }
}
let x = new Foo();
console.log("bar" in x);

Also if I create an Interface with an attribute it will not allow me to create a class that doesnt implements the attribute (as expected), but with the attribute it creates the same resulting JS like in the first example.

interface Bar{
    bar : string;
}
class Foo implements Bar{
    bar : string;
}

let x = new Foo();
console.log("bar" in x); // returns false

It seems like this behaviour is wanted, but I dont get the point or any advantage (is there any ?). And is there a way I can make Typescript to create undefined attributes, without changing the original TS ?

0 Answers
Related