Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 626
A T Avatar asked Sep 23 '15 22:09

A T


1 Answers

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);
}
like image 178
thoughtrepo Avatar answered Sep 29 '22 21:09

thoughtrepo