TypeScript constructor - environmental error

How to create a constructor in TypeScript?

I looked at a bunch of manuals, but the syntax should have changed. Here is my last attempt:

car.d.ts

declare class Car {
    constructor(public engine: string) {
        this.engine = engine + "foo";
    }
}

Mistake:

Implementation cannot be invoked in surrounding contexts.

+4
source share
1 answer

Using declare, you determine the type of class. The type is defined only and should not have an implementation, so declareyou must delete it. Then it compiles fine.

class Car {
    constructor(public engine: string) {
        this.engine = engine + "foo";
    }
}

However, this code compiles into:

var Car = (function () {
    function Car(engine) {
        this.engine = engine;
        this.engine = engine + "foo";
    }
    return Car;
})();

which sets the property twice engine.

This is probably not what you intended, so the property engineshould be defined in the class, not in the constructor.

class Car {

    public engine: string;

    constructor(engine: string) {
        this.engine = engine + "foo";
    }
}

Edit:

, declare, , .d.ts . .ts, , JavaScript.

2:

declare class Car {

    public engine;

    constructor(engine: string);
}
+5

Source: https://habr.com/ru/post/1608743/


All Articles