Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript abstract method using lambda/arrow function

I am using TypeScript 1.6 and would like to create an abstract class with an abstract method but use a lambda/arrow function in the concrete class.

Is this possible? The code shown below does not compile as it says

"Class 'Base' defines instance member function 'def', but extended class 'Concrete' defines it as instance member property"...

abstract class Base {
    abstract abc(): void;
    abstract def(): void;
}

class Concrete extends Base {
    private setting: boolean;

    public abc(): void  {
        this.setting = true;
    }

    public def = (): void => {
        this.setting = false;
    }
}
like image 314
Craig Broadman Avatar asked Oct 29 '15 09:10

Craig Broadman


2 Answers

My understanding of Typescript specifications is that when you are declaring

public def = (): void => {
    this.setting = false;
}

You are actually declaring a property called def and not a method on the Base class.

Properties cannot (unfortunately IMHO) be abstracted in Typescript: https://github.com/Microsoft/TypeScript/issues/4669

like image 176
Bruno Grieder Avatar answered Sep 30 '22 01:09

Bruno Grieder


You can use an abstract property:

abstract class Base {    
    abstract def: () => void; // This is the abstract property
}

class Concrete extends Base {
    private setting: boolean;    

    public def = (): void => {
        this.setting = false;
    }
}

var myVar: Base = new Concrete();
myVar.def();
console.log((myVar as any).setting); // gives false
like image 31
user764754 Avatar answered Sep 30 '22 03:09

user764754