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.
The override specifier was a killer feature in c++ 11. It so much helps and protects refactoring code. I definitely would like to have this in TS base support without any hurdles (VOTE!)
We've definitely shown wild support for this feature, but it seems they still don't plan on adding this feature anytime soon.
Another idea:
class Obj {
static override<
This extends typeof Obj,
Over extends keyof InstanceType<This> = never,
>(this: This, ...overs: Over[]) {
return this as This & (
new(...a:any[])=> InstanceType<This> & Protect< Omit<InstanceType<This> , Over > >
)
}
}
class Foo extends Obj {
bar(a: number) {
return 0
}
bar2(a: number) {
return 0
}
foo = 1
}
class Foo2 extends Foo.override('bar') {
foo = 2
bar( a : number ) {
return 1
}
// Error: Class 'Foo & Protect<Pick<Foo, "bar2" | "foo">>'
// defines instance member property 'bar2',
// but extended class 'Foo2' defines it as instance member function.
bar2( a : number ) {
return 1
}
bar3( a : number ) {
return 1
}
}
declare const Protected: unique symbol
type Protect<Obj> = {
[Field in keyof Obj]:
Object extends () => any
? Obj[Field] & { [Protected]: true }
: Obj[Field]
}
Adding my two cents here. We have a typical angular component, that handles forms and needs to unsubscribe from valueChanges and such. We didn't want to repeat the code all over the place (kinda current state), so I've made a "TypicalFormBaseComponent" that (among other things) implements angulars OnInit and OnDestroy methods. The issue is that now if you actually use it and add your own OnDestroy method (which is pretty standard thing to do), you hide the original one and break the system. calling super.OnInit fixes it, but there is currently no mechanism for me to force the children to do that.
If you do it with the constructor, it forces you to call super()... I was looking for something similar, found this thread, and honestly, I am kinda bummed. Implementing "new" and "override" in the ts might be a breaking change, but fixing it would be incredibly simple in basically any codebase (just adding 'override' everywhere where it screams). It might also be just a warning.
Anyways, is there some other way for me to force the super call in the children? TSLint rule that prevents hiding, or something like that?
PS: I don't agree with the "no comment" policy. It prevents people from throwing examples here. Maybe you won't implement 'override', but you'll implement something else, that takes care of their problems... that is, if you can actually read them.
@GonziHere In other languages such as C# or Java, overriding does not imply the requirement to call the super method - it often is not the case in fact. Constructors are special and not normal "virtual methods".
The override keyword would be used to specify that the method must already be defined with a compatible signature on the base class, and the compiler could assert this.
Yes, but the need for override forces you to notice that the method exists.
@GonziHere Look like what you may really need is to create abstract base classes with abstract functions. Perhaps you can create private _onInit and _onDestroy methods you can more rely on, then create protected onInit and onDestroy abstract functions (or regular functions if they are not requried). The private functions will call the others, then complete as normal.
@GonziHere @rjamesnw The safe thing to do is actually to somehow enforce that onInit and onDestroy are final, and define empty protected abstract template methods that the final methods call. This guarantees that nobody can accidentally override the methods, and trying to do so (assuming there were a way to enforce final methods) would immediately point users to the right way to implement what they want.
@shicks, @rjamesnw, I'm in the same situation as @GonziHere. I don't want the base class to have abstract methods because there is functionality that I want executed for each of those lifecycle hooks. The problem is that I don't want that base functionality to be accidentally replaced when someone adds ngOnInit or ngOnDestroy on the child class without calling super(). Requiring override would bring to the attention of the dev that those methods exist in the base class and that they should choose if they need to call super();
From my experience writing Java, @Override is so common that it becomes noise. In many cases, the overridden method is abstract or empty (where super() should not be called), making the presence of override not a particularly clear signal that super() is needed.
From my experience writing Java,
@Overrideis so common that it becomes noise. In many cases, the overridden method is abstract or empty (wheresuper()should not be called), making the presence ofoverridenot a particularly clear signal thatsuper()is needed.
That has nothing to do with the subject at hand. You might just as well said to use composition over inheritance to avoid the problem.
For me, the most useful part of override is to get an error while refactoring.
Right now it is all too easy to rename some method in a base class and forget to rename the ones that override it.
Remembering to call super is not that important. It is even correct to not call it in some cases.
I think that there is a misunderstanding on why the override would be important. Not to force someone to call the super() method, but to make them aware that one exists and allow them to conscientiously decide whether they want to suppress its behavior or extend it.
The pattern I use to ensure correctness is to use Parameters and ReturnType while referring very explicitly to the base class, something like this:
class Base {
public methodName(arg1: string, arg2: number): boolean {
return false; // base behaviour, may be stub.
}
}
class Derived extends Base {
public methodName(...args: Parameters<Base["methodName"]>): ReturnType<Base["methodName"]> {
const [meaningful, variableNames] = args;
return true; // implemented behaviour here.
}
}
This kind of pattern is the basis for my suggestion to add an inherit keyword.. This ensures that any updates to the base class automatically propagate and if invalid in the derived class then an error is given, or of the name changes of the base class then an error is also given, also with the inherit idea you aren't constrained to only offer identical signature to the base class but can intuitively extend it.
I also think there's a misunderstanding about why override would be important, but I don't really understand all these issues with "whether super() is needed".
To echo what @lorenzodallavecchia and the original author of the issue have said, marking a function as override is a mechanism to avoid screw-ups that happen when the superclass is refactored, specifically when the name and/or signature of the overridden function changes or the function is removed.
Keep in mind that the person changing the signature of the overridden function may not be aware that overrides exist. If (e.g. in C++) the overrides are not explicitly marked as overrides, then changing the name/signature of the overridden function does not introduce a compilation error, it simply causes those overrides to no longer be overrides. (and.. probably no longer be useful, no longer be called by code that used to call them, and introduce a bunch of new bugs because things that are supposed to call the overrides are now calling the base implementation)
The override keyword, as implemented in C++, saves the person changing the base implementation from these problems, because immediately after their refactoring, compilation errors will indicate to them that a bunch of overrides exist (that override a now-nonexistent base implementation) and clue them in to the fact that they probably need to refactor the overrides as well.
There are secondary IDE usability benefits to having the override modifier as well (also mentioned by original author), namely that upon typing the word override the IDE can helpfully show you a bunch of possibilities of what can be overridden.
Together with the override keyword it would be good to also introduce a flag that, when enabled, requires that all methods that override another uses the override keyword, so as to avoid cases where you create a method in a subclass and in the future the base class (that could be in a 3rd party library) creates a method with the same name as the method you created in the subclass (which could cause bugs now, because the subclass had overridden that method).
Getting a compilation error in this case, saying that you need to add the override keyword in this method (even tough you may not actually override the method, just change its name so as to not override the newly created method in the base class), would be much better and avoid possible runtime bugs.
From my experience writing Java, @Override is so common that it becomes noise.
After many Java-years I strongly disagree with above statement. Override is a way of communication, like checked exceptions. It's not about like or dislike, but about quality and expectations.
And therefore a big +1 to @lucasbasquerotto , but from another point of view: if I introduce a method in a subclass I want to have a clear semantic of overriding or not overriding. For example if I want to override a method, then I want to have a way to tell that explicitly. If something wrong with my implementation, for example a typo or wrong copy&paste, then I want to get feedback about it. Or other way: if I don't expect to override, I want feedback too, if overriding occasionally happens.
Feedback from another Java developer... @override is the only feature I'm really missing from Typescript.
I have ~15 of Java experience and 1-2 years or Typescript so pretty comfortable with both.
The zen of @override is you can remove a method from an interface and the compilation will break.
It's like the reverse of tight binding for new methods. It allows you to remove old ones.
If you implement an interface and ADD a method the compilation will fail but there isn't an inverse of this.
If you remove a method you'll just end up with dead code.
(though maybe that can be fixed by a linter)
To be clear, when I said that @Override was noise, I was specifically referring to the comment about it being a signal that you need to call super. The checking it provides is valuable, but for any given overridden method, it's a complete toss-up whether it's required or pointless to call super. Since such a large fraction of overridden methods shouldn't, it's ineffective for that purpose.
My entire point is that if you want to ensure subclasses call back into your overrideable methods, the only effective way to do that is to make the method final (see #33446, among others) and have it call into a differently-named empty template method that can be safely overridden without the super call. There's simply no other reasonable way to get that invariant. I'm completely in favor of override, but as someone who's been burned by users incorrectly subclassing my APIs (and I'm on the hook not to break them), I believe it's worth shifting attention to final as the correct solution to this issue, rather than override as was suggested upthread.
I'm a little confused as to why people keeps suggesting one of final or override over the other. Surely we want both, as they solve different problems.
Override Prevents people who are extending a class from accidentally overwriting a function with their own, breaking things in the process without even knowing. Having an override keyword lets the developer know that they are in fact overriding an existing function, and then they can choose to either rename their function or use the override (and then they can find out if they need to call super).
Final Prevent people who are extending a class from overwriting a function completely, so that the original creator of the class can guarantee complete control.