A T
A T

Reputation: 13836

TypeScript constructor - ambient contexts error

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:

car.d.ts

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

Error:

An implementation cannot be called in ambient contexts.

Upvotes: 9

Views: 12912

Answers (1)

thoughtrepo
thoughtrepo

Reputation: 8383

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);
}

Upvotes: 12

Related Questions