TypeScript icon indicating copy to clipboard operation
TypeScript copied to clipboard

Suggestion: abstract classes

Open RyanCavanaugh opened this issue 12 years ago • 50 comments

Support an abstract keyword for classes and their methods

Examples:

abstract class Base {
    abstract getThing(): string;
    getOtherThing() { return 'hello'; }
}
var x = new Base(); // Error, 'Base' is abstract

// Error, must either be 'abstract' or implement concrete 'getThing'
class Derived1 extends Base { }

class Derived2 extends Base {
    getThing() { return 'hello'; }
    foo() { super.getThing(); } // Error: cannot invoke abstract members through 'super'
}
var x = new Derived2(); // OK
var y: Base = new Derived2(); // Also OK
y.getThing(); // OK
y.getOtherThing(); // OK

abstract class Empty { } // OK

RyanCavanaugh avatar Jul 15 '14 16:07 RyanCavanaugh

I would say prevent directly instantiating abstract classes at compile time. Otherwise let it be a run time error. It works the same way in other statically typed languages.

// e.g. C#
object value = new Stream(); // compile time error

Type type = typeof(Stream);
value = Activator.CreateInstance(type); // this compiles fine but will fail at runtime

What about something like this to prevent runtime instantiation?

// TypeScript
abstract class GreeterBase {
    greeting: string;
    constructor(message: string) {
        this.greeting = message;
    }
    abstract greet(): void;
}

class Greeter extends GreeterBase {
    constructor() {
        super("World");
    }

    greet() {
        alert("Hello, " + this.greeting);
    }
}
// JavaScript
var GreeterBase = (function () {
    function GreeterBase(message) {
        throw new Error("Cannot instantiate abstract class");
    }
    GreeterBase.prototype.__ctor = function (message) {
        this.greeting = message;
    }
    return GreeterBase;
})();
var Greeter = (function (_super) {
    __extends(Greeter, _super);
    function Greeter() {
        _super.prototype.__ctor.call(this, "World");
    }
    Greeter.prototype.greet = function () {
        alert("Hello, " + this.greeting);
    };
    return Greeter;
})(GreeterBase);

enoshixi avatar Dec 19 '14 19:12 enoshixi

That sounds like the best solution.

Sent from my iPhone

On 19 Dec 2014, at 19:20, enoshixi [email protected] wrote:

I would say prevent directly instantiating abstract classes at compile time. Otherwise let it be a run time error. It works the same way in other statically typed languages.

// e.g. C# object value = new Stream(); // compile time error

Type type = typeof(Stream); value = Activator.CreateInstance(type); // this compiles fine but will fail at runtime What about something like this to prevent runtime instantiation?

// TypeScript abstract class GreeterBase { greeting: string; constructor(message: string) { this.greeting = message; } abstract greet(); }

class Greeter extends GreeterBase { constructor() { super("World"); }

greet() {
    "Hello, " + this.greeting;
}

} // JavaScript var GreeterBase = (function () { function GreeterBase(message) { throw new Error("Cannot instantiate abstract class"); } GreeterBase.prototype.__ctor = function (message) { this.greeting = message; } return GreeterBase; })(); var Greeter = (function (_super) { __extends(Greeter, _super); function Greeter() { _super.prototype.__ctor.call(this, "World"); } Greeter.prototype.greet = function () { "Hello, " + this.greeting; }; return Greeter; })(GreeterBase); — Reply to this email directly or view it on GitHub.

nathggns avatar Dec 19 '14 19:12 nathggns

@enoshixi Exactly what I was trying to suggest, but much better presented!

Griffork avatar Dec 20 '14 00:12 Griffork

Just an idea of a more JScript oriented implementation of abstract methods, without abstract classes

class GreetBase {
    greeting: string;
    constructor(message: string) {
        this.greeting = message;
    }
    greet:()=>void;
}

class Greeter extends GreeterBase {
    greet() {
        console.log("Hello, " + this.greeting);
    }
}

and used as

function logGreet() {
    console.log( "Log: " + this.greeting );
}

var gr =  new Greeter("World");
gr.greet = logGreet; // supply implementation on the fly
gr.greet(); // "Log: World"
delete gr.greet; // back to prototyped
gr.greet(); // "Hello, World"

var gBase = new GreetBase("Abstract");
gBase.greet = logGreet; // supply implementation on the fly
gBase.greet(); // "Log: Abstract"
delete gBase.greet; // back to default
gBase.greet(); // error

If you wanted to prevent public construction of GreetBase then perhaps the constructor could be decorated with "protected"

panost avatar Dec 21 '14 13:12 panost

Regarding throwing an error from the constructor of the abstract class, I would rather abstract be a design-time check only. We have cases where we want to write test cases for abstract classes, so the following should be permitted:

  var sut: MyAbtractClass = new (<any>MyAbtractClass)();

  assert.areEqual('foo', sut.foo);

I'm aware there are workarounds (e.g. create a mock derived class); not very eager to do that. A runtime error also doesn't really fit in with design goal number 1:

Statically identify constructs that are likely to be errors.

@RyanCavanaugh, the compiler should issue an error for the factory method case. It's always possible to workaround that quite easily, similar to the test case above:

var j: Abs = new (<any>t)();

Not clear about this:

attempting to prevent it would require a lot of extra type system mechanics.

Is that because of the aliasing?

NoelAbrahams avatar Dec 22 '14 10:12 NoelAbrahams

@NoelAbrahams How many other languages that have abstract classes allow you to override their abstract nature and make them anyway? I for one would prefer having to derive from classes in my tests of that meant that catching runtime errors would be easier (particularly for refactoring). We have a system in place that may actually allow abstract classes to be initialised when they shouldn't which would bypass all of the static type checking, so run- time errors in abstract classes would be a huge time saver.

Griffork avatar Dec 22 '14 11:12 Griffork

I like the run time error. If you end up accidentally instantiating an abstract class you are likely to receive a run time error anyway (and not getting an error would almost be worse). I'd rather have it fail quickly and obviously.

Maybe some extra syntax could be used to opt-in or out of the error?

abstract class GreeterBase with Error("Cannot instantiate abstract class") { }

enoshixi avatar Dec 22 '14 18:12 enoshixi

Or a flag -abstractdontthrowerror?

That way you could turn off the error on client code and leave it in for development (or vice versa)

Griffork avatar Dec 22 '14 22:12 Griffork

I don't think there's sufficient value in automatically generating a runtime check. People who really want that behavior would always be free to add that to their classes. Adding runtime checks for type system constraints is not something TypeScript does in general.

The code posted by @enoshixi is not workable in practice because you don't know whether any given declare abstract class was generated by TypeScript (in which case the compiler needs to emit __ctor.call) or is a declaration for a "plain" JavaScript class (in which case the compiler needs to emit the normal super call). We'd really rather not complicate the ambient declaration system to the point where people need to know special syntax for one kind of abstract class versus another.

RyanCavanaugh avatar Dec 30 '14 05:12 RyanCavanaugh

Huh, hadn't considered the declare problem before, good catch @RyanCavanaugh. Without the ability to have a run-time check, abstract classes are actually not giving Typescript developers anything new; you can already define class methods that will either error or not be assigned to within the typescript language; the largest bonus here is the ability to essentially "override" the constructor in a similar manner to the way the error-throwing methods can be overridden.

In JavaScript I had a number of "hacks" for implementing runtime-error abstract classes (e.g. THREE.js' prototype copying). I am sad that not only is this not available in Typescript, with the current implementation of classes it is pretty much not possible in Typescript (you can't opt-in to it at all).

Excepting of course, completely forgoing Typescript's classes and mimicking them with JavaScript code.

[EDIT] P.S. You can probably realise at this point that at work I have no problem with people purposefully instantiating "abstract" classes (commenting can prevent someone from doing this) but I have a problem with a more automatic means of creating objects sometimes creating objects that are supposed to be "abstract". Pain Point.

Griffork avatar Dec 30 '14 06:12 Griffork

@Griffork how do you define class methods that are not assigned ?

mwisnicki avatar Dec 30 '14 16:12 mwisnicki

@Griffork if you want runtime checks perhaps you would be interested in this.

mwisnicki avatar Dec 30 '14 16:12 mwisnicki

Is that (Edit: Safe & Efficient Gradual Typing for TypeScript) actually available? Also, it seems a little overkill. As I said in another thread, I deal with software that needs to be performant. I'm happy with the idea of developers getting to choose whether or not the constructor throws an error (possibly even with a keyword), but Typescript has made it very difficult to do that at all.

In Javascript you could do something like this:

//Extends
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 __();
};
//Parent (modified from the Typescript example)
var AbstractGreeter = (function () {
    function AbstractGreeter(message) {
        throw new Error("Can not instantiate parent directly");
    }
    AbstractGreeter.prototype.init = function (message) {
        this.greeting = message;
    };
    AbstractGreeter.prototype.greet = function () {
        return "Hello, " + this.greeting;
    };
    return AbstractGreeter;
})();
//Child, doesn't call super(), therefore doesn't trigger the run-time error.
var Greeter = (function (_super) {
    __extends(Greeter, _super);
    function Greeter(message) {
        _super.prototype.init.call(this, message);
    }
    return Greeter;
})(AbstractGreeter);

In Typescript, you have to forgo all class support to achieve the same effect (or live with little red squiggles everywhere).

Typescript Attempt:

//Code copied from typescript output.
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 __();
};

class AbstractGreeter {
    greeting: string;
    constructor(message: string) {

    }
    init(message: string) {
        this.greeting = message;
                //If we need to (e.g. if we're extending from another class) we can call
               //super.init.apply(this, arguments) or super.apply(this, arguments) here.
    }
    greet() {
        return "Hello, " + this.greeting;
    }
}

//Code copied from a typescript generated class, and then modified.
var Greeter = (function (_super) {
    __extends(Greeter, _super);
    function Greeter() {
        var _this = this;
        _super.prototype.init.apply(this, arguments);
        this.greet = function () {
            return "Hello, " + _this.greeting;
        };
    }
    return Greeter;
})(AbstractGreeter);

var greeter = new Greeter("world"); //Error, Supplied parameters do not match any signature of call target. Only a void function can be called with the 'new' keyword.

Errors in Typescript but the compiled code runs anyway. It's also a pain to maintain (about as much of a pain as JavaScript is, which is why we switched to Typescript).

I'm ok with using another keyword to mark-up which abstract classes have run-time errors in their constructors and which don't, if that turns out to be the 'best' solution, but run-time errors for these things would be invaluable.


@mwisnicki To declare methods and not have them assigned you can use the following code:

class AbstractGreeter {
    greeting: string;
    constructor(message: string) {
        this.greeting = message;
    }
    greet: ()=>void;
}

class Greeter extends AbstractGreeter {
    greet = () => {
        return "Hello, " + this.greeting;
    }
}

It may not have the syntax that you prefer, but it is actually doable in Typescript's current class structure. The primary problem here is that there is no way of declaring functions as needing to be overridden (you will get no red squiggles or compile-time errors).


Conclusion: By default abstract methods will error at run time because they're not defined (this already happens). So the abstract keyword needs only add compile-time checks. Abstract classes have no run-time or compile-time errors, it would be best if Typescript could supply both; in a System where classes can be instantiated by ID instead of hard-coded, you can't ensure that some classes won't be instantiated at some point. And often those errors can take hours, days or weeks to track down.

Griffork avatar Dec 31 '14 01:12 Griffork

Just posting this here in case anyone wants to have a "throws at runtime" abstract constructor that still works for derived cases:

function abstract<T>(ths: { constructor: T }, cls: { prototype: T } ) {
    if(Object.getPrototypeOf && (Object.getPrototypeOf(ths) === cls.prototype)) throw new Error('This class is abstract')
}

class Abs {
    constructor() {
        abstract(this, Abs);

        // Other ctor logic here
    }
}

class Concrete extends Abs {
} 

var x = new Abs(); // Throws
var y = new Concrete(); // OK

RyanCavanaugh avatar Dec 31 '14 18:12 RyanCavanaugh

@Griffork I don't think it's available but I hope their work will some day find its way into TypeScript compiler, perhaps as an option. Full type safety with runtime checks may not be appropriate for high performance libraries but for usual application code it would help a lot. But in the end there is no single solution that will satisfy everyone. Ideally I'd like tsc to provide some api/hooks that let people customize code generation so you can output whatever checks you need and target whatever JS class library/pattern you want.


@Griffork As for your undefined abstract method example, I don't see the point of doing it the way you did - besides ugly syntax you get no compile time check (obviously) and worst of all you waste memory on per instance property instead of using prototype like normal method would. With current syntax limitations it's better to just define normal method that throws exception.

mwisnicki avatar Dec 31 '14 19:12 mwisnicki

@RyanCavanaugh thanks for that, I totally didn't think of that!

Griffork avatar Feb 01 '15 00:02 Griffork

This would also be really useful for me.

One solution to avoid having to implement a runtime check could be to just not implement the abstract method in the abstract class in javascript, and let it throw a TypeError if you somehow manage to instantiate the abstract class and try to call an abstract method. It's not perfect, but it respects typescript philosophy of not doing anything typescript specific in the generated javascript and already helps a lot.

It could look like this:

class AbstractGreeter {
    constructor(private name: string) {}

    greet() {
        return this.salutation() + ", " + this.name;
    }

    abstract salutation(): string;
}

class HiGreeter extends AbstractGreeter {
    salutation(): string {
        return "hi";
    }
}

var g = new AbstractGreeter("Typescript");  //compile error
var ctor = AbstractGreeter;

function makeMaybe(ctor): AbstractGreeter {
    if(Math.random() > 0.5) {
        return new ctor("Typescript");
    }
    else {
        return null;
    }
}

var ag1 = new AbstractGreeter("Typescript"); //compile error

var hg = makeMaybe(HiGreeter); //compiles
if(hg) {
    console.log(hg.greet()); //logs "hi, Typescript"
}

var ag = makeMaybe(AbstractGreeter); //compiles 
if(ag) {
    console.log(ag.greet()); //throws "TypeError: undefined is not a function"
}

With the generated javascript looking like this, not defining salutation() in AbstractGreeter:

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 AbstractGreeter = (function () {
    function AbstractGreeter(name) {
        this.name = name;
    }
    AbstractGreeter.prototype.greet = function () {
        return this.salutation() + ", " + this.name;
    };
    return AbstractGreeter;
})();
var HiGreeter = (function (_super) {
    __extends(HiGreeter, _super);
    function HiGreeter() {
        _super.apply(this, arguments);
    }
    HiGreeter.prototype.salutation = function () {
        return "hi";
    };
    return HiGreeter;
})(AbstractGreeter);
var g = new AbstractGreeter("Typescript"); //compile error
var ctor = AbstractGreeter;
function makeMaybe(ctor) {
    if (Math.random() > 0.5) {
        return new ctor("Typescript");
    }
    else {
        return null;
    }
}
var ag1 = new AbstractGreeter("Typescript"); //compile error
var hg = makeMaybe(HiGreeter); //compiles
if (hg) {
    console.log(hg.greet()); //logs "hi, Typescript"
}
var ag = makeMaybe(AbstractGreeter); //compiles 
if (ag) {
    console.log(ag.greet()); //throws "TypeError: undefined is not a function"
}

bwindels avatar Feb 12 '15 16:02 bwindels

Thinking about the above example. I don't know how elaborate the type system is inside the compiler, but wouldn't the compiler be able to determine in the example above that the makeMaybe() function receives constructor of an abstract class and in some cases that constructor function is used with the new operator inside the function?

bwindels avatar Feb 12 '15 16:02 bwindels

My concern is a long story that involves dynamic require statements (requires that are given a variable instead of a hard coded string). Those required files export one class, and that class is created at run time. Some bugs have caused abstract classes to be instantiated in this manner, which isn't ideal, this the request for the ability for the constructor to be able to error if not called by a derived class. Note: some of these abstract classes don't contain any virtual functions (all functions have implementation) but they are not 'complete' enough to be used for anything in their own.

I was hoping for native Typescript support for that, but since I'll be able to write the check myself that works too. As long as I can avoid the hours it took to find out I was instantiating an abstract class that it did the first time ;-).

Griffork avatar Feb 12 '15 21:02 Griffork

+1 to include the feature as a compile-only error (without throwing errors in the constructor). All I want is to know that I've forgotten to override a method. It would be awesome if Intellisense in Visual Studio could generate stubs for you when you begin defining a class which extends the abstract class. IMO, the benefit of Typescript revolves around composing code, not changing the execution behavior. I've been waiting for abstract classes for a while, for that purpose : to help me write code, and catch errors at compile time.

bryanrideshark avatar Mar 17 '15 21:03 bryanrideshark