Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to have functions in base class, but lambda functions in sub class?

Tags:

typescript

I'm using a third party api that has a d.ts definitions where a class have functions declared like so:

export class Bar {
    foo(): void;
}

now when I create an implementation of a sub class I want to use lambda function syntax

    export class Test1 extends Bar {
         public foo = (): void => {
              //DO Stuff
         }
    }

This does not compile because

"Class 'Test1' defines instance member property 'foo', but extended class 'Bar' defines it as instance member function."

Do I need to change the definition of the Bar-class for it to work with lambda-functions? I'd rather not, so if there is some other solution I'd appreciate the help!

Update

Ok, so i noticed something. If I instead of extends use implements, I'm allowed to use lamdba functions in Test1. To me it sounds weird to implement a class. The Bar-class does sort of look like a interface, could it be because of that it works?

like image 280
Gustav Avatar asked Sep 05 '14 10:09

Gustav


1 Answers

If you use implements, you won't actually inherit from the base class - so if that base class had other properties and methods that you were hoping to access you would find them all absent from you Test1 class.

When using implements you would have to implement all properties and methods specified in the structure.

Here is the transpiled JavaScript:

var Foo = (function () {
    function Foo() {
        this.foo = function () {
        };
    }
    return Foo;
})();

If you use extends the compiler will emit additional code that extends your Test1 class with the methods and properties of the base class.

When using extends you can optionally override methods, but do not have to implement all members as you inherit them from the base class.

Here is the transpiled JavaScript (you can see the additional code):

var __extends = this.__extends || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    __.prototype = b.prototype;
    d.prototype = new __();
};
var Foo = (function (_super) {
    __extends(Foo, _super);
    function Foo() {
        _super.apply(this, arguments);
    }
    Foo.prototype.foo = function () {
    };
    return Foo;
})(Bar);
like image 62
Fenton Avatar answered Nov 25 '22 01:11

Fenton