Suggestion: abstract classes
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
:+1:
The example would be more awesome if you incorporate virtual as well. :smile:
abstract class Base {
abstract getThing(): string;
getOtherThing() { return 'hello'; }
virtual getVirtualThing() { return 'hello virtual'; }
}
...
@am11 given that methods in JS get called by traversing the prototype chain, all methods are already "virtual" in the traditional sense that C++, C#, Java, and similar languages define it.
For instance:
class E {
f () { alert("E"); }
}
class F extends E {
f () { alert("F"); }
}
var x: E = new F();
x.f();
will alert "F".
Did you have something else in mind?
@DanielRosenwasser, that is so true. Thanks!
Actually, I was thinking about the conventional OO keywords virtual and overrirde, so its easy to clearly differentiate between various inheritance behaviors. The TS compiler might just throw warning if those keywords are missing in applicable scenarios and fallback to standard JS convention.
I believe this way we can bring C#'s new modifier as well:
abstract class A {
public void foo() { }
protected virtual void bar() { }
}
class A1 : A {
protected override void bar() { }
}
there may exist A2, such that:
class A2 : A {
public new void foo() { }
}
to explicitly hide super's implementation (without new keyword there, CS compiler gives warning).
new is infeasible given JavaScript's runtime semantics; given that we've already shipped the language this way, virtual would be the default in the absence of any other modifier. Let's take discussion of those modifiers to a different suggestion if needed.
Seems like the example above has enough information to discuss. Some open questions:
- Can I have an abstract class with zero abstract methods?
- Is the
abstractmodifier implicit in a class that doesn't implement allabstractmethods?
Can I have an abstract class with zero abstract methods?
Since abstract class -- in principle -- serves a purpose of grouping commonalities together such that its objects alone don't make sense; I think we should rule no_abstract_method as a legit case and let the TypeScript linter take care of recommending best practices, code-styling et el.
Is the abstract modifier implicit in a class that doesn't implement all
abstractmethods?
Given an abstract class would be able to inherit another abstract class, implicit inference like this would be confusing? I guess (at least C#/Java) developers would expect compiler to throw error and editor to help them correct it, if the first non-abstract / concrete implementer is missing any expected override. Well as a Ruby guy, I'd probably appreciate this kind of crypto-magic :`)
Even before abstract is implemented, I'm still hoping you'd allow intellisense kick in (in Visual Studio) when overriding base class functions:
class BaseClass {
myFunction() { /* TO BE OVERRIDDEN */ }
}
class MyClass extends BaseClass {
myF // intellisense should have kicked in -- but it doesn't
}
My only option is to open BaseClass.ts to check I'm spelling it correctly.
I'd still prefer to see more descriptive keywords, as I mentioned on https://typescript.codeplex.com/discussions/449920
| C# | VB (on classes) | VB (on methods) |
|---|---|---|
abstract |
MustInherit |
MustOverride |
virtual |
Overridable |
Overridable |
sealed |
NotInheritable |
NotOverridable |
From these more descriptive keywords, it can be seen immediately that the overridable keyword is unnecessary as methods in JavaScript are overridable by default as opposed to in C# and is less likely to lead to confusion demonstrated by @am11. I believe the same gain in clarity is achieved with the other keywords listed.
We're trying to clear out our design backlog and I think this should come up soon once ES6 features are wrapped up. We discussed abstract in a design meeting a few months ago and there didn't seem to be any big open questions.
The standard design pattern in JS is to throw an exception in the abstract class:
function Base() { throw new Error("Not implemented."); }
Base.prototype.f = function () { throw new Error("Not implemented."); };
Base.prototype.g = function () { /* default impl */ };
function Derived() {}
Derived.prototype.f = function () { /* impl */ };
Derived.prototype.g = function () { /* override impl */ };
The benefit TypeScript could provide is reducing boilerplate and a compile-time error.
Discussed today in the design meeting.
The open question here is how we prevent you from trying to instantiate an abstract class. Consider some code:
abstract class Abs {
constructor() { /* some general init here */ }
}
var x = new Abs(); // Desired: error
This case is easy -- when you invoke new on a symbol, we see if the symbol is a class with abstract, and error if so.
Next:
var a = Abs;
var x = new a(); // Not a good thing to do
This is less obvious. You probably want an error? But then consider this case:
class B extends Abs { /* ... */ }
class C extends Abs { /* ... */ }
var t: typeof Abs;
if(/*... */) {
t = B;
} else {
t = C;
}
var j = new t(); // This is fine
There's nothing distinguishing this case from the previous one (in terms of the type system), but the latter is perfectly valid code to write (and would probably even be common code to write in a factory method). We will probably have to not error on the new a(); case, both because it mimics a valid pattern and because attempting to prevent it would require a lot of extra type system mechanics.
What about an hidden field?
Let's say we have a class
abstract class Abs {
constructor() { /* some general init here */ }
}
Because the class is abstract, we cannot instanciate it, you said you wanted to check if the class was abstract or not to do so. What if having a abstract class would generate somehow hidden field ___abstract___ = true. If the class isn't abstract like with class B extends Abs { /* ... */ } then we would have the ___abstract___ = false, so to check if a class is abstract or not we could just check that hidden field.
I don't know if it's a proper solution, or even if it's possible, but the point is to check if the closest class is abstract or not, whatever if it extends and abstract class or not.
I think, you don't have to go crazy with this. I believe, the main thing that people want from this is to be able to get a compile-time error on non-implemented abstract methods and also to omit implementation of interface methods in abstract classes. The rest is great, but not that crucial. Start small and extend if needed.
Abstract type shouldn't have visible constructor. i.e. new t() in above example shall fail.
If user wants constructible type he should explicitly allow it which is possible thanks to type unions:
var t: typeof Abs | new() => Abs;
I would have thought that a type being abstract would be a bit in the type system. That's how people code it up in other functional languages. Then the compiler maintains knowledge of which types are abstract and which are concrete. Make sense?
I wouldn't mind if the typeof corner-case doesn't catch abstract.
I feel the common use case is to simply define abstract methods that are left for child classes to implement.
I like two proposed solutions personally,
- Abstract classes are type only, they have no code and what would be their code is added to child classes code.
- don't handle the typeof case. Here's something else too: abstract classes could have an init method instead of a constructor, and their constructor could error. The init method must be called by child classes (like super ()) and must be bound to a child instance. Init methods on abstract class must call their parent's constructor or init. This leaves the constructor free to contain a throw new error and still have child classes be able to work correctly. The method doesn't need to be called init, and can be marked with an underscore or something if deemed necessary.
@Griffork, your first proposition wouldn't allow for someChild instanceof MyAbstractClass at runtime
@RyanCavanaugh, instances like your typeof example is when I really hate static typing. With static typing this shouldn't be allowed because there is a chance that variable holds an abstract class. In an ideal world, the compiler would "run" the code and only error in the case I've assigned non-abstract classes to the variable (not the case in your example).
Also, are you definitely going with the abstract keyword?
I don't think any alternatives have even been mentioned.
I think mustoverride would be a more descriptive keyword for abstract methods
For alternatives in other scenarios that you may use abstract, please see my comment above
To spell it out, I think mustoverride, mustinherit, notoverridable and notinheritable are more descriptive keywords
@RamIdeas Good point, didn't think of that.
Alternatives to mustoverride and mustinherit that are more descriptive of the current behaviour than the intended use case would include notcallable and notnewable.
After all, you can't garentee how something is going to be used, but you can garentee it's state, and that's what the abstract and virtual keywords were designed to do.