Support override keyword on class methods
(Update by @RyanCavanuagh)
Please see this comment before asking for "any updates", "please add this now", etc.. Comments not meaningfully adding to the discussion will be removed to keep the thread length somewhat reasonable.
(NOTE, this is not a duplicate of Issue #1524. The proposal here is more along the lines of the C++ override specifier, which makes much more sense for typescript)
An override keyword would be immensely useful in typescript. It would be an optional keyword on any method that overrides a super class method, and similar to the override specifier in C++ would indicate an intent that "the name+signature of this method should always match the name+signature of a super class method". This catches a whole range of issues in larger code bases that can otherwise be easily missed.
Again similar to C++, it is not an error to omit the override keyword from an overridden method. In this case the compiler just acts exactly as it currently does, and skips the extra compile time checks associated with the override keyword. This allows for the more complex untyped javascript scenarios where the derived class override does not exactly match the signature of the base class.
Example use
class Animal {
move(meters:number):void {
}
}
class Snake extends Animal {
override move(meters:number):void {
}
}
Example compile error conditions
// Add an additional param to move, unaware that the intent was
// to override a specific signature in the base class
class Snake extends Animal {
override move(meters:number, height:number):void {
}
}
// COMPILE ERROR: Snake super does not define move(meters:number,height:number):void
// Rename the function in the base class, unaware that a derived class
// existed that was overriding the same method and hence it needs renaming as well
class Animal {
megamove(meters:number):void {
}
}
// COMPILE ERROR: Snake super does not define move(meters:number):void
// Require the function to now return a bool, unaware that a derived class
// existed that was still using void, and hence it needs updating
class Animal {
move(meters:number):bool {
}
}
// COMPILE ERROR: Snake super does not define move(meters:number):void
IntelliSense
As well as additional compile time validation, the override keyword provides a mechanism for typescript intellisense to easily display and select available super methods, where the intent is to specifically override one of them in a derived class. Currently this is very clunky and involves browsing through the super class chain, finding the method you want to override, and then copy pasting it in to the derived class to guarantee the signatures match.
Proposed IntelliSense mechanism
Within a class declaration:
- type override
- An auto complete drop down appears of all super methods for the class
- A method is selected in the drop down
- The signature for the method is emitted into the class declaration after the override keyword.
I was not aware of https://github.com/Microsoft/TypeScript/pull/6118. The idea looks like a possible alternative to adding override.
If I understood the problem properly, the issue is that you can have more than one base classes / interfaces with compatible but not identical member declarations, and they have to be unified when being initialized in the child class without a type.
Without having a good idea of the consequences, I would be happy if:
- the member will produce a compile-time error that requires explicit type declaration on the child class
- the member will take the intersection of all the possible types.
More important IMO would be to have some way of triggering auto-completion when writing class members (Ctrl+Space). When the cursor is directly inside of a class, you could be defining new members of re-defining inherited ones, so the auto-completion can not be too aggressive, but with manual triggering the behavior should be OK.
Regarding @RyanCavanaugh comments:
We definitely understand the use cases here. The problem is that adding it at this stage in the language adds more confusion than it removes. A class with 5 methods, of which 3 are marked override, wouldn't imply that the other 2 aren't overrides. To justify its existence, the modifier would really need to divide the world more cleanly than that.
Typing a variable as any doesn't imply that some other variable is or isn't also any. But, there is a compiler flat --no-implicit-any to enforce that we explicitly declare it. We could equally have a --no-implicit-override, which I for one would turn on if it were available.
Having an override keyword that is used gives developers an enormous amount of insight when reading code that they are unfamiliar with, and the ability to enforce it would give some additional compile time control.
For all the +1ers -- can you talk about what's not sufficient about the decorator solution shown above?
Is there any way in which a decorator a better solution than an override keyword? There are many reasons why it is worse: 1) It adds runtime overhead however small; 2) It's not a compile time check; 3) I have to include this code to every one of my libraries; 4) There is not way for this to catch functions that are missing the override keyword.
Let's give an example. I have a library with three classes ChildA, ChildB, Base. I've added some method doSomething() to ChildA and ChildB. After some refactoring, I've added some additional logic, optimized, and moved doSomething() to the Base class. Meanwhile, I have another project which depends on my library. There I have ChildC with doSomething(). There is no way when I update my dependencies to find out that ChildC is now implicitly overriding doSomething(), but in an unoptimized way that is also missing some checks. That is why an @overrides decorator will never be sufficient.
What we need is an override keyword, and a --no-implicit-override compiler flag.
An override keyword would help me a lot since I use in my project a simple hierarchy of base classes to create all my components. My problem lies in the fact that these components may need to declare a method to be used somewhere else, and this method may or may not be defined in a parent class and may or may not already do stuff that I need.
For example, let's say that a function validate takes a class with a getValue() method as parameter. To build this class, I can inherit another class that could already define this getValue() method, but I can't really know this unless I look at its source code. What I'd instinctively do is implement this method in my own class, and as long as the signature is correct no one will tell me anything.
But maybe I shouldn't have done that. The following possibilities all suppose that I did an implicit override:
- The base class already defined this method just like I did, so I wrote a function for nothing. Not that much of a problem.
- I incorrectly rewrote the function, most of the time because I forgot to do some non-obvious stuff that was already handled by the base class. What I really needed to do here is call
superin my override, but no one suggested me to do so.
Having a mandatory override keyword would have told me "hey, you're overriding, so maybe you should check what the original method looks like before doing your stuff". That would greatly improve my experience with inheritance.
Of course, as suggested, it should be placed under a --no-implicit-override flag since it would be a breaking change and that most people do not care that much about all this.
I like the comparaison @eggers made with any and --no-implicit-any because it's the same kind of annotation and it would work in the exact same way.
@olmobrutall I was looking at some of your talk about overriding abstract methods & interface methods.
If my opinion, override implies the existence of a super. Neither abstract methods nor methods defined in an interface can be called via a super. call, and so should not be overrideable (there is nothing to override). Instead if we do something more explicit for those cases, it should be an implements keyword. But, that would be a separate feature discussion.
Here are the problems as I see them, ranked most important to least. Did I miss anything?
Failure to override
It's easy to think you're overriding a base class method when you're not:
class Base {
hasFilename(f: string) { return true; }
}
class Derived extends Base {
// oops
hasFileName(f: string) { return false; }
}
This is probably the biggest problem.
Failure to implement
This is very closely related, especially when the implemented interface has optional properties:
interface NeatMethods {
hasFilename?(f: string): boolean;
}
class Mine implements NeatMethods {
// oops
hasFileName(f: string) { return false; }
}
This is a less important problem than failure to override, but it's still bad.
Accidental override
It's possible to override a base class method without realizing it
class Base {
hasFilename(f: string) { return true; }
}
class Derived extends Base {
// I didn't know there was a base method with this name, so oops?
hasFilename(f: string) { return true; }
}
This should be relatively rare just because the space of possible method names is very large, and the odds that you'd also write a compatible signature and not mean to have been doing this in the first place are low.
Accidental anys
It's easy to think that override methods will get the parameter types of their base:
class Base {
hasFilename(f: string) { return true; }
}
class Derived extends Base {
// oops
hasFilename(f) { return f.lentgh > 0; }
}
We tried to type these parameters automatically but ran into problems. If hasFilename were explicitly marked override we might be able to solve those problems more easily.
Readability
It's not immediately clear when a method is overriding a base class method and when it's not. This seems like a smaller problem because there are reasonable workarounds available today (comments, decorators).
Editor experience
You have to manually type out base method names when writing derived class override methods, which is annoying. We could easily fix this by always providing those names in the completion list (I think we actually have a bug on this already), so we don't really need a language feature to fix this problem.
Non-problems
Listing these out as things that either belong in a separate issue or simply aren't going to happen:
- Exact signature matching -- this isn't something that should be mixed in with
override, and it really does have undesirable semantics in many good scenarios - Insufficiently exotic syntax (e.g.
implements.foo = ...). No need to bikeshed here
@RyanCavanaugh I agree with all of the above in about that order as well. Just as a comment, I don't think that the override keyword should be solving the "failure to implement" problem. As I said above, I think that problem should be solved by a different keyword (e.g. implements) as part of a different ticket. (override should imply a super. method)
@RyanCavanaugh I agree with all the points but I don't see any reference to the also very related problem of initialized fields declared in a parent type without overriding the type (and then loosing type checking). I think the feature should not be confined to method declarations in a language where methods are just functions in object fields.
@eggers even if at the end the end two keywords are needed, the semantics will be very similar and I think the features should be discussed together.
override should imply a super. method
In C# override can (and must) be used also for abstract methods (with no .super). In Java @override is an attribute. Of course they are different language but with similar keywords you expect similar behaviors.
I agree with @RyanCavanaugh 's points, though I'd say the "accidental override" problem might be a little more common than he believes (especially when dealing with extending a class that already extends something else, like a React component that would already define a componentWillMount method in the first extension).
I believe though, like @eggers said, that the "failure to implement" issue is something pretty different, and it would feel weird to use an override keyword for a method that doesn't exist in a parent class. I know these are different languages with different problematics, but in C# override isn't used for interfaces. I would suggest, if we could get a --no-implicit-override flag, that interface methods would have to be prefixed with the interface name (which would look a lot like C# and thus feel more natural).
Something like
interface IBase {
method1?(): void
}
class Base {
method2() { return true; }
}
class Test extends Base implements IBase {
IBase.method1() { }
override method2() { return true; }
}
I think @RyanCavanaugh lists the fundamental problems. I would complement that with "What are the disagreements":
- Is declaring a method to match an interface considered an
override? For example:
interface IDrawable
{
draw?( centerPoint: Point ): void;
}
class Square implements IDrawable
{
draw( centerPoint: Point ): void; // is this an override?
}
- is declaring a property to match an interface considered an
override?
interface IPoint2
{
x?: number;
y?: number;
}
class Circle implements IPoint2
{
x: number; // is this an override?
y: number; // is this an override?
radius: number;
}
- Is there a need for some kind of
implementskeyword, to handle the above cases instead of anoverridekeyword, and the form it would take.
@kevmeister68 thanks for explicitly stating the disagreements.
One thing: you have to make the interface members optional to really show the problem, like this the typescript compiler will complain when a field or method is not implemented, solving "Failure to implement".
@olmobrutall Thanks for that. I've never declared a method optional - can it be (I come from a C# background and there is no such concept)? I've updated the examples I listed above to change the member variables to optional - is that better?
@kevmeister68 also the draw method in IDrawable :)
@RyanCavanaugh
Insufficiently exotic syntax (e.g. implements.foo = ...). No need to bikeshed here
Thanks for teaching me a new expression. I don't see a lot of problems in the semantics of the feature:
- We all want compile-time errors if the method does not exist
- We all want compile-time errors the type does not match.
- We also want that the parameters are implicitly typed to the parent one, like lambda expressions do.
- We want some IDE help to write the method properly.
Most of the problems rely on the syntax and the behaviours that they impliy:
- Optional members in Interface vs members in Base classes
- Methods vs fields (don't know where lambdas will be)
Let's compare the tree more promising syntaxes:
override / implements
class Person{
dateOfBirth: Date;
abstract talk();
walk(){ //...}
}
interface ICanFly{
fly?();
altitude?: number;
}
class SuperMan extends Person implements ICanFly {
dateOfBirth = new Date(); //what goes here?
override talk(){/*...*/}
walk = () => {/* force 'this' to be captured*/} //what goes here
implements fly() {/*...*/}
altitude = 1000; //what goes here?
}
Advantages:
- It's natural for programmers with OO background.
- Feels right when comparing with
extends/implements.
Disadvantages:
- Doesn't provide a solution to the field problem, none
overrideorimplementsfeels right. Maybesuper., but then what we do with interfaces? - If the methods are overridden using a lambda (useful to capture this) of a
function()the same problems happens.
override / InterfaceName.
class Person{
dateOfBirth: Date;
abstract talk();
walk(){ //...}
}
interface ICanFly{
fly?();
altitude?: number;
}
class SuperMan extends Person implements ICanFly {
dateOfBirth = new Date(); //what goes here?
override talk(){/*...*/}
walk = () => {/* force 'this' to be captured*/} //what goes here
ICanFly.fly() {/*...*/}
ICanFly.altitude = 1000; //what goes here?
}
Advantages:
- Is also natural for programmers with OO background.
- Solves the field problem for interfaces, but not for classes, but we could use
super.for them.
Disadvantages:
- Interface names can be long, specially with generics, and showing the auto-competition list will also be problematic, requiring some Alt+Space to make it explicit.
- Makes it looks like you can implement two members with the same name from different interfaces independently. This works in C# but won't work in Javascript.
this.
class Person{
dateOfBirth: Date;
abstract talk();
walk(){ //...}
}
interface ICanFly{
fly?();
altitude?: number;
}
class SuperMan extends Person implements ICanFly {
this.dateOfBirth = new Date();
this.talk(){/*...*/}
this.walk = () => {/* force 'this' to be captured*/}
this.fly() {/*...*/}
this.altitude = 1000;
}
Advantages:
- Solves classes, interfaces, methods and fields.
- Uses (abuses?) just one pre-existing keyword.
- Using
this.to trigger auto-completion feels natural. - Makes clear that the object is just one namespace, and you can only have one thing for each name.
Disadvantages:
- Looks like an expression, not a declaration, making it hard to parse for non-trained eyes.
Whilst failure to implement a non-optional interface method will cause a compiler error, if the interface changes at some point in the future (lets say a method is removed) there will be no warning for all classes that implemented that method. This might not be as big an issue as optional's but I think it's fair to say the scope of this goes beyond them.
I do however, still believe override is a distinctly different thing and potentially having two keywords rather than one would better convey the intent of the program.
For example, consider a scenario where a developer believes they are implementing an interface method when in-fact they're overriding the method which has already been declared in a base class. With two keywords the compiler can prevent this kind of mistake and throw an error to the tone of method already implemented in a base class.
interface IDelegate {
execute?() : void;
}
class Base implements IDelegate {
implement public execute() : void { /// fine, this is correctly implementing execute
}
}
class Derived extends Base {
implement public execute() : void {
/// ERROR: `method "execute():void" already implemented in a base class`
}
}
I don't know if this is relevant in JS, but class fields are supposed to be private in OO, so I don't think we need to be overriding fields explicitly since the fact that they're private already prevent us to override altogether.
Instance methods are fields though, and from what I gather a lot of people use them instead of prototype methods. About that,
class Person{
walk(){ //...}
}
class SuperMan extends Person {
walk = () => {/* force 'this' to be captured*/}
}
is a compiler error, because walk is a prototype method in Person and an instance method in SuperMan.
Anyway, i'm not sure override would be a fit here, because well, we don't override fields. Again, it would look like C#, but I'd rather use the new keyword instead of override here. Because it's not the same thing as a method override (I can call super.myMethod in an override, not here).
My preferred solution would then be something like (assuming we're in strict override mode):
class Person{
dateOfBirth: Date;
talk() { }
walk = () => { }
}
interface ICanFly {
fly?();
altitude?: number;
}
class SuperMan extends Person implements ICanFly {
new dateOfBirth = new Date();
override talk() { }
new walk = () => { }
implements fly() {/*...*/}
implements altitude = 1000;
}
My main concern is about interfaces though. We shouldn't have to write implements for non optional interface members, because we'll be already caught by the compiler. Then, if we do so, there'll be a confusion between what is from an interface and what isn't, since not all interfaces members would be prefixed by implements. And that word is a mouthful. I'm not ready to write something like this:
class C extends React.Component {
implements componentWillMount() { }
implements componentDidMount() { }
implements componentWillReceiveProps(props) { }
/// ... and the list goes on
}
I proposed to prefix with the interface name earlier but @olmobrutall showed me that it was a worse idea.
Anyway, I'm pretty convinced that we'll need 3 different new keywords to properly tackle this.
I also don't think that it's necessary to implicitly type the overrides since the compiler will already prevent us to write something that's not compatible, especially because it is apparently difficult to do right.
Isn't new, override and implement too much keyword overhead for essentially the same JS semantics? Even if in C# they are different things there is virtual no difference in JS/TS.
It's also quite ambiguous:
- Why fields are
newfor classes butimplementsfor interfaces? - If you're changing a method from a base class that was implemented with an interface what should you use? I can see four possibilities:
override,implements, any of the two or both at the same time?
Also think about this:
class Animal {
}
class Human extends Animal {
}
class Habitat {
owner: Animal;
}
class House extends Habitat {
owner = new Human();
}
var house = new House();
house.owner = new Dog(); //Should this be allowed??
The question is:
Does owner = new Human(); re-define the field with a new (but compatible) type, or just assigns a value.
I think in general you re-defined the field except if you using the magic keyword. My preference is for this. right now.
class House extends Habitat {
this.owner = new Human(); //just setting a value, the type is still Animal
}
@olmobrutall That might indeed be a bit much keyword overhead, but all 3 are indeed different things.
overridewould apply to methods (defined on the prototype), meaning that it does not erase the original method, which is still accessible behindsuper.newwould apply to fields, and mean that the original field has been erased by the new one.implementswould apply to anything from an interface, and mean that it does not erase or replace anything that already existed in a parent class, because an interface "doesn't exist".
If you're changing a method from a base class that was implemented with an interface what should you use? I can see four possibilities: override , implements , any of the two or both at the same time?
It seems pretty logical to me that it would be override since that what you're effectively doing here. implements would mean that you're implementing something from the interface that doesn't exist otherwise. In a sense, override and new would have priority over implements.
And about your field override exemple, nothing should change about how it works today. I'm not sure what happens here, but whatever it is it shouldn't change (or maybe it should, but that's not what we're discussing here).
I feel that override would be suitable for both base methods and properties, including abstract ones (explained below).
new is an interesting idea in concept, but this particular keyword may be confused with class instantiation, so it may give the false impression it would only work for classes, despite the fact that properties can have primitive, interface, union or even function types. Perhaps a different keyword like reassign could work better there, but it has the problem that it may give a false idea in the case the value is only re-declared but not actually assigned with anything in the derived class (new may have that problem as well). I think redefine is also interesting, but could lead to the mistaken expectation that the 'redefined' property could also have a different type than the base one, so I'm not sure.. (edit: actually I checked and it could have a different type as long as the new one is a subtype of the base one, so this may not be that bad).
implement (I prefer this particular verb form for consistency with override) seems to work for interfaces. I believe it could also technically work for abstract base methods as well, but using override could feel more consistent, despite the slightly different semantics. Another reason is that it would make it a bit inconvenient to change a method from abstract to non-abstract, as one would need and go to all the derived classes and change override to implement.
There could be better ideas, but that's all I have at this point..
I proposed the keyword new because it's the one C# uses for this exact feature, but I agree this isn't the best one. implement is indeed a better choice over implements. I don't think we should use it for abstract methods since they're part of a base class and not an interface. override + new -> base class, implement -> interface. That seems clearer.
@JabX
About overriding prototype with instance field
I've checked and you're right:
class Person{
walk(){ //...}
}
class SuperMan extends Person {
walk = () => {/* force 'this' to be captured*/}
}
Fails with Compiler error: Class 'Person' defines instance member function 'walk', but extended class 'SuperMan' defines it as instance member property.
I don't really see the reason to fail in this case, since the parent type contract is fulfilled and you can write this anyway:
var p = new SuperMan();
p.walk = () => { };
Or even
class SuperMan extends Person {
constructor() {
super();
this.walk = () => { };
}
}
About override
override would apply to methods (defined on the prototype), meaning that it does not erase the original method, which is still accessible behind super.
That's actually an argument. There is least some observable difference between override and implements... but not quite.
Both override and implements are implemented in the prototype, being able to use super is independent, because you call super.walk() not just super(), and is available in every method ( overrides, implements, news and normal definitions).
class SuperMan extends Person implements ICanFly {
new dateOfBirth = new Date();
override talk() { } //goes to prototype
new walk = () => { }
implements fly() {/*...*/} //also goes to the prototype
implements altitude = 1000;
}
And being able to use super.walk() also works if you assign to the instance
class SuperMan extends Person {
constructor() {
super();
this.walk = () => { super.walk(); };
}
//or with the this. syntax
this.walk = () => { super.walk(); };
}
There's already a clear way to differentiate prototype fields from instance fields and is the = token.
class SuperMan extends Person implements ICanFly {
this.dateOfBirth = new Date(); //instance
this.talk() { } //prototype
this.walk = () => { } //instance
this.fly() {/*...*/} //prototype
this.altitude = 1000; //instance
}
With the this. syntax the problem is solved more elegantly:
this.means check my type (base classes and implemented interfaces).=means assign to the instance instead of the prototype.
About New
newwould apply to fields, and mean that the original field has been erased by the new one.
Take into account that you can not change the field or method with a different type because you will break the type system. In C# or Java when you do new the new method will be used only on statically dispatched calls to the new type. In Javascript all the calls will be dynamic and if you change the type the code will likely break at run-time (Coercing the type could be allowed for practical purposes however, but not widening).
class Person {
walk() { }
run() {
this.walk();
this.walk();
this.walk();
}
}
class SuperMan extends Person {
new walk(destination: string) { } //Even if you write `new` this code will break
}
So more than new the keyword should be assign, because this is the only type-safe thing you can do:
class Person{
dateOfBirth: Date;
}
class SuperMan extends Person implements ICanFly {
assign dateOfBirth = new Date();
}
Note that reassign doesn't make sense, because Person only declares the field but doesn't set any value on it.
Writing assign seems redundant however, it's clear that we're assigning because we have a = at the other side.
Again the this. syntax solves the problem gracefully:
class Person{
dateOfBirth: Date;
}
class SuperMan extends Person implements ICanFly {
this.dateOfBirth = new Date();
}