When you use declare
, you are essentially defining a class type without any implementation. It is necessary to remove the declare
in order for the code to compile correctly.
class Car {
constructor(public engine: string) {
this.engine = engine + "foo";
}
}
However, after compilation, the code looks like this:
var Car = (function () {
function Car(engine) {
this.engine = engine;
this.engine = engine + "foo";
}
return Car;
})();
This results in setting the engine
property twice, which may not be your intended behavior. The engine
property should be defined on the class rather than within the constructor.
class Car {
public engine: string;
constructor(engine: string) {
this.engine = engine + "foo";
}
}
Edit:
If you received an error about needing to use declare
, it might be because of the .d.ts
extension used for definition files. For proper JavaScript compilation, consider using just the .ts
extension.
Edit 2:
declare class Car {
public engine;
constructor(engine: string);
}