8

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

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

That would certainly make the error message make a lot more sense. Unfortunately, my def method makes a call to a function that returns a promise and inside of the promise callback I need to refer to "this" hence the reason I want to use a lambda/arrow function. Therefore I guess my only other option is to use var self = this; etc
2

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

1 Comment

Cool, got the understanding now.
0

You could do that starting typescript 2.0. In order to make that work you would need to declare a type for your arrow function

type defFuntion = () => void;

then declare

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

here is a reference for this feature

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.