How do I create a constructor in TypeScript?
Looked at a bunch of guides, but the syntax must've changed. Here's my latest attempt:
declare class Car {
constructor(public engine: string) {
this.engine = engine + "foo";
}
}
An implementation cannot be called in ambient contexts.
By using declare
you're defining a class type. The type is only defined, and shouldn't have an implementation, so declare
needs to be removed. Then it compiles fine.
class Car {
constructor(public engine: string) {
this.engine = engine + "foo";
}
}
However that code compiles to:
var Car = (function () {
function Car(engine) {
this.engine = engine;
this.engine = engine + "foo";
}
return Car;
})();
which sets the engine
property twice.
That probably wasn't what you intended, so the engine
property should be defined on the class, not the constructor.
class Car {
public engine: string;
constructor(engine: string) {
this.engine = engine + "foo";
}
}
Edit:
The error you received about needing declare
was due to you using the .d.ts
extension for definition files. The extension should be just .ts
if you want the file to compile to JavaScript.
Edit 2:
declare class Car {
public engine;
constructor(engine: string);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With