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 felt the need for an 'override' specifier, too. In medium to large projects, this feature becomes essential and with all due respect I hope the Typescript team will reconsider the decision to decline this suggestion.
For anyone interested we've written a custom tslint rule that provides the same functionality as the override keyword by using a decorator, similar to Ryan's suggestion above but checked at compile-time. We'll be open-sourcing it soon, I'll post back when it's available.
I strongly felt necessity of 'override' keyword, too. In my case, I changed some of method name in a base class and I forgot to rename some of names of overriding methods. Of course, this leads some of bugs.
But, If there was such a feature, we can find these class methods easily.
As @RyanCavanaugh mentioned, if this keyword is just a optional keyword, this feature makes confusion. So, how about to make something flag in tsc to enable this feature?
Please reconsider this feature again....
To me, if the override keyword is to be useful, it needs to be enforced, like it is in C#. If you specify a method in C# that overrides the signature of a base method, you must label it either override or new.
C++ is annoying and inferior compared to C# in some places because it makes too many keywords optional, and therefore precludes consistency. For example, if you overload a virtual method, the overloaded method can be marked virtual or not - either way it will be virtual. I prefer the latter because it aids other developers who read the code, but I can't get the compiler to enforce it being put in, which means our code-base will undoubtedly have missing virtual keywords where they should really be. The override keyword is similarly optional. Both are crap in my opinion. What is overlooked here is that code can serve as documentation and improve maintainability by enforcing the need for keywords rather than a "take it or leave it" approach. The "throw" keyword in C++ is similar.
To achieve the above objective in TypeScript, the compiler needs a flag to "enable" this stringent behaviour or not.
Insofar as the function signatures of the base and the override are concerned, they should be identical. But it would be desirable to allow covariance in the specification of the return type to enforce a compile-time check.
I'm coming to TS from AS3 so of course, I'm going to throw my vote here for an override keyword as well. To a developer who's new to any given codebase, seeing an override is a huge clue as to what might be going on in a (child) class. I think such a keyword hugely adds value. I would opt to make it mandatory, but I can see how that would be a breaking change and so should be optional. I really don't see a problem with the ambiguity that imposes, though I am sensitive to the difference between an optional override and the default public keyword.
For all the +1ers -- can you talk about what's not sufficient about the decorator solution shown above?
To me it feels like an artificial construct, not a property of the language itself. And I guess that's by design, because that's what it is. Which I guess sends developer (well, me anyway) the message that it's transient, not a best practice.
obviously every language has its own paradigm and, being new to TypeScript I'm slow with the paradigm shift. I have to say though that override DOES feel like a best practice to me for a number of reasons. I'm making the switch to TypeScript because I have fully swallowed the strongly-typed koolaid, and believe that the cost (in terms of keystrokes and learning curve) is heavily outweighed by the benefits both to error-free code and code comprehension. override is a very important piece of that puzzle, and communicates some very important information about the role of the overriding method.
For me it's less about IDE convenience, though that is undeniably awesome when properly supported, and more about fulfilling what I believe to be the principles upon which you've built this language.
@RyanCavanaugh some issues that I see:
- The decorator syntax will be harder for IDEs to provide code completion (yeah, I guess it could be done but they would need prior knowledge)
- The derived class could change the visibility of a method - which in strict terms shouldn't be allowed
- Difficult for the decorator to check the argument list and types, and compatible return type
The compiler is already checking the argument list and return type, though. And I think even if override did exist as a first-class keyword, we wouldn't enforce some new rule about signature identicalness
And I think even if override did exist as a first-class keyword, we wouldn't enforce some new rule about signature identicalness.
@RyanCavanaugh then I think you might be on a different page about the intent of the keyword. The whole point of it is for cases where you want to enforce signature identicalness. This is for the design pattern where you have a deep complex hierarchy sitting on a base class that defines a contract of interface methods, and all classes in the hierarchy must exactly match those signatures. By adding the override keyword on these methods in all the derived classes, you are alerted to any cases where the signature diverges from the contract set out in the base class.
As I keep saying this is not some esoteric use case. When working on a large code bases (with say hundreds or thousands of classes) this is an every day occurrence, ie someone needs to change the signature of the base class (modify the contract), and you want the compiler to alert you to any cases throughout the hierarchy that no longer match.
The compiler will already warn of illegal overrides. The issue with the current implementation is the lack of intent when declaring an overridden method.
The decorator mentioned before just seems to go against what the language is trying to achieve. There shouldn't be a runtime cost incurred for something that can be dealt with at compile time, however small the cost. We want to catch as much stuff going wrong as possible, without needing to run the code to find out.
It's possible to achieve using the decorator and custom a custom tslint rule, but would be better for the tooling ecosystem and the community for the language to have an official keyword.
I think being optional is one approach, but as with with some C++ compilers there are flags you can set which enforce its use (e.g. suggest-override, inconsistent-missing-override). This would seem the best approach to avoid breaking changes and seems consistent with other new features being added recently such as nullable types and decorators.
On Wed, 23 Mar 2016 at 21:31, Rowan Wyborn [email protected] wrote:
And I think even if override did exist as a first-class keyword, we wouldn't enforce some new rule about signature identicalness.
@RyanCavanaugh https://github.com/RyanCavanaugh then I think you might be on a different page about the intent of the keyword. The whole point of it is for cases where you want to enforce signature identicalness. This is for the design pattern where you have a deep complex hierarchy sitting on a base class that defines a contract of interface methods, and all classes in the hierarchy must exactly match those signatures. By adding the override keyword on these methods in all the derived classes, you are alerted to any cases where the signature diverges from the contract set out in the base class.
As I keep saying this is not some esoteric use case. When working on a large code bases (with say hundreds or thousands of classes) this is an every day occurrence, ie someone needs to change the signature of the base class (modify the contract), and you want the compiler to alert you to any cases throughout the hierarchy that no longer match.
— You are receiving this because you are subscribed to this thread. Reply to this email directly or view it on GitHub https://github.com/Microsoft/TypeScript/issues/2000#issuecomment-200551774
@kungfusheep fwiw the compiler only catches a certain class of illegal overrides, that is where there is a direct clash between declared params. It does not catch the addition or removal of params, nor does it catch return type changes. These extra checks are what any override keyword would switch on.
The compiler correctly warns you if you add a parameter to an overriding function.
Removing a parameter, though, is totally valid:
class BaseEventHandler {
handleEvent(e: EventArgs, timestamp: number) { }
}
class DerivedEventHandler extends BaseEventHandler {
handleEvent(e: EventArgs) {
// I don't need timestamp, it's OK
}
}
Changing the return type is also totally valid:
class Base {
specialClone(): Base { ... }
}
class Derived extends Base {
specialClone(): Derived { ... }
}
@RyanCavanaugh yes they are valid from a strict language perspective, but this is why I started using the term "contract" above. If a base class lays out a specific signature, when I use override I am stating that I want my derived class to strictly follow that signature. If the base class adds additional params or changes return type, I want to know every point in my code base that no longer matches, as the contract they were originally written against has now changed in some way.
The idea of having a big class hierarchy each with its own slightly different permutations of the base methods (even if they are valid from a language perspective) is nightmare inducing and takes me back to the bad old days of javascript before typescript came along :)
If the optionality is the main problem with the keyword, then why not make it mandatory when the base class method is defined as abstract? This way, if you wanted to enforce the pattern strictly you could simply add an abstract base class. To avoid breaking code a compiler switch could disable the check.
We seem to be talking about two different sets of expectations now. There's the missing-override/illegal override situation and then there's the explicit signature one. Can we all agree the former is the absolute bare-minimum we'd expect from this keyword?
I only say this because there are other ways of enforcing explicit method signatures currently, such as interfaces, but there is currently no way of explicitly stating the intent to override.
Ok, there is no way of enforcing explicit signatures of overridden methods but given that the compiler enforces that any signature changes are at least 'safe' then it seems like there is a separate conversation to be had around the solution to that problem.
Yeah agreed. If I had to choose, the missing-override/illegal override situation is the more important problem to solve.
I'm a bit late to the party... I think the whole point of Typescript is to enforce rules at compile-time, not at runtime, otherwise we'd all be using plain Javascript. Also, it's a bit weird to use hacks/kludges to do things that are standard in so many languages.
Should there be an override keyword in Typescript? I certainly believe so. Should it be mandatory? For compatibility reasons I'd say its behavior could be specified with a compiler argument. Should it enforce the exact signature? I think this should be a separate discussion, but I haven't had any problem with the current behavior so far.
The original reason for closing this seems to be that we cannot introduce the breaking change that all overridden methods needs the override specifier, which would make it confusing since the methods not marked with override could also in fact be overrides.
Why not enforce it, either with a compiler option, and/or if there is at least one method marked override in the class, then all methods that are overrides must be marked as such, otherwise it is an error?
Is it worth reopening this whilst it's up in the air?
On Fri, 8 Apr 2016 at 14:38, Peter Palotas [email protected] wrote:
The original reason for closing this seems to be that we cannot introduce the breaking change that all overridden methods needs the override specifier, which would make it confusing since the methods not marked with 'override' could also in fact be overrides.
Why not enforce it, either with a compiler option, and/or if there is at least 'one' method marked override in the class, then all methods that are overrides must be marked as such, otherwise it is an error?
— You are receiving this because you were mentioned. Reply to this email directly or view it on GitHub https://github.com/Microsoft/TypeScript/issues/2000#issuecomment-207434898