Aleksandr Gorin Aleksandr Gorin - 2 months ago 9
TypeScript Question

TypeScript: how can generate constructor function?

I want to make correct constructor function on TypeScript, but I have problem. I've tried a lot of options, but the result is still no :(

My last version TS code: open Playground

Typescript appends to my code excess function:
enter image description here

See generated code:

(function () {
function UserModule(arg1, arg2, arg3) {
var UserModule = (function () {
function UserModule(section, where) {
this.arg1 = arg1;
this.arg2 = arg2;
this.arg3 = arg3;
this.section = section;
this.getElem('');
return this;
}
UserModule.prototype.getElem = function (new_elem) {
this.section + this.arg1;
return this;
};
return UserModule;
}());
}
})();


I want code:

(function () {
function UserModule(arg1, arg2, arg3) {
function UserModule(section, where) {
this.arg1 = arg1;
this.arg2 = arg2;
this.arg3 = arg3;
this.section = section;
this.getElem('');
return this;
}
UserModule.prototype.getElem = function (new_elem) {
this.section + this.arg1;
return this;
};
return UserModule;
}
})();


Please help me remove this function. Thanks all!

TNU TNU
Answer

You are not supposed to alter the compiled JavaScript files. The 'excess' functions is there to implement class UserModule for you in JavaScript.

Update:

It look like you want to create different instances of your service. Implementing angular factories in TypeScript is fairly straightforward, by simply defining your service class locally in the service provider function.

See the implementation below:

interface IUserModelService {
    getElement: (param: string) => string;
}

function UserModelServiceProvider(
    $scope: ng.IScope,
    $http: ng.IHttpService
) {
    class UserModelService implements IUserModelService {
        constructor(
            private selection: string,
            private where: string
        ) { }
        public getElement(param: string) {
            return param + this.selection + this.where;
        }
    }
    return (selection: string, where: string) => {
        return new UserModelService(selection, where);
    };
}

yourAngularApp.factory("userModel", UserModelServiceProvider);

You can then inject this "userModel" into your controller, and use it to create your service instances.