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'm probably missing something, but in Javascript (and thus Typescript) you cannot have 2 methods with the same name - even if they have different signatures?
In C#, you could have
public string method(string blah) {};
public int method(int blah) {};
But here you can never have 2 functions with the same name, no matter what you do with the signatures... so none of your examples would ever be possible anyway, right? Unless we're talking about multiple extends on the same class... but that is not what your examples are showing, so probably not? Is this a non-issue?
Right now I'm using inheritance, and it is very frustrating... I'm having to put comments about functions to indicate that they're virtual (ie. I'm overriding them somewhere) or override (ie. that this function is overriding an underlying function). Super annoying and messy! And unsafe!
@sam-s4s Yes it is possible to declare multiple logical overload signatures for a method, but they all end up on the same single implementation (which then has to figure out by the passed parameters which "overload" is being called). This is heavily used by many JS frameworks, for instance jQuery where $(function) adds a ready function, but $(string) searches the DOM by selector.
See here for the docs: https://www.typescriptlang.org/docs/handbook/functions.html#overloads
@avonwyss Ah yes, declarations, but not implementations, that makes sense :) Thank you
This has gone on waaay too long, and i find it annoying that I have to read this entire bloated thread to even begin to figure out why TS still does not have this basic compile-time assertion.
Where are we on either (a) an override keyword or (b) an @override jsdoc annotation that informs the compiler "a method having the same name and type signature MUST exist on a superclass."?
More specifically, does the comment in https://github.com/Microsoft/TypeScript/issues/2000#issuecomment-224776519 (Jun 8 2016) by @RyanCavanaugh suggest that the next step is a (community) PR?
class Bar extends Foo {
/**
* @override
*/
public toString(): string {
// ...
}
override public toString(): string {
// ...
}
}
More specifically, does the comment in #2000 (comment) (Jun 8 2016) by @RyanCavanaugh suggest that the next step is a (community) PR?
@pcj Correct
I've started a PR on this at #13217. Anyone else interested in this functionality is most welcome to participate and/or provide suggestions. Thanks!
I would prefer the same as for java with a decorator
@Override
public toString(): string {
// ...
}
@Chris2011 Agree this looks familiar, but this would imply as a decorator that @Override would be evaluated at runtime, not compile-time. I am planning javadoc /** @override */ in a separate PR once #13217 override keyword (public override toString()) moves forward in review.
Trying to follow the conversation of this thread. Does this include static functions? I don't see any reason why we couldn't also allow overriding static functions in derived classes with completely different signatures. This is supported in ES6. If had class A { } ; A.create = function (){} then class B extends A { } ; B.create = function (x,y) { }, calling A.create() is not going to call B.create() and cause issues. For this reason (and to create the ability to use the same function name on types as factory functions) you should also allow override the signature of base static functions. It's doesn't break anything, and adds the ability to do some neat stuff (especially for game engine frameworks, where 'new' anything is really an evil if used all the time without pulling from a cache of objects to reduce GC freezes). Since callable constructors are not supported under ES6, creating a common naming convention for methods on types is the only other option; however, doing so currently requires the derived static function to show an overload of the base static function signature along with it's own, which is not useful for a factory function on a type that only deals with THAT type. :/ In the mean time the only option I have is to force users of my framework to duplicate all base hierarchy static function signatures (such as SomeType.create()) on their derived types, and so on, which just gets really silly.
Here is an example about the "silliness" I'm talking about (which works, but not something I'd be proud of in an extensible framework):
class A {
static create(s: string) {
var inst: A;
/* new or from cache */
inst.init(s);
}
protected init(s: string) { }
}
class B extends A {
static create(s: string);
static create(n: number);
static create(n:any) {
var inst: B;
/* new or from cache */
inst.init(n);
}
protected init(s: string);
protected init(n: number);
protected init(n: any) {
super.init(n.toString());
}
}
class C extends B {
static create(s: string)
static create(n: number)
static create(b: boolean)
static create(b: any) {
var inst: C;
/* new or from cache */
inst.init(b);
}
protected init(s: string);
protected init(n: number);
protected init(b: boolean);
protected init(b: any) {
super.init(b ? 0 : 1);
}
}
(https://goo.gl/G01Aku)
This would have been much nicer:
class A {
static create(s: string) {
var inst: A;
/* new or from cache */
inst.init(s);
}
protected init(s: string) { }
}
class B extends A {
new static create(n:number) {
var inst: B;
/* new or from cache */
inst.init(n);
}
new protected init(n: number) {
super.init(n.toString());
}
}
class C extends B {
new static create(b: boolean) {
var inst: C;
/* new or from cache */
inst.init(b);
}
new protected init(b: boolean) {
super.init(b ? 0 : 1);
}
}
@rjamesnw you may be interested in Polymorphic "this" for static members having a contract for factory functions is discussed as a primary use case throughout the comments.
so, again restating a feeling that @pcj expressed (comment) over a year ago, it's confusing to have to read so many PRs and comments here and elsewhere to determine where this feature request is at.
it seems like #13217 was so close, then shot down again by @DanielRosenwasser and company as a feature that may not fit the language, seemingly re-entering the circular conversation here on this issue about whether or not it should be done. Maybe this 'design-time' decorators (#2900) thing will solve it, maybe not? It'd be nice to know.
Here's a few more shortcomings of the runtime decorator approach posted a few years ago that I didn't see mentioned:
- It won't work with properties since they're not part of the prototype
- Properties and accessors can (sort-of...) override one another, which also won't work
- We have abstract classes now, but since abstract things don't actually exist at runtime, it can't possibly work with them
If the only caveat was that the checks occurred upon class initialisation then I could probably accept it as a temporary measure, but as is there are just too many limitations.
Frankly I cannot believe this feature is still so controversial over 3 years since I first logged the issue. Every "serious" object oriented language supports this keyword, C#, F#, C++... you name it.
You can argue hypotheticals all day long about why javascript is different and needs a different approach. But from a practical perspective working daily in a very large Typescript code base, I can tell you that override would make a huge difference to code readability and maintenance. It would also eliminate an entire class of bugs due to derived classes accidentally overriding base class methods with compatible but subtly different signatures.
I would really love to see a proper implementation of virtual / override / final. I'd be using it all the time, and it would make code so much more readable and less error-prone. I feel like this is an important feature.
Agreed. It's frustrating to see how relatively obscure / edge-case features are being added, while something so... fundamental is being rejected. Is there anything we can do to push for this?
Come on people! If there is this many comments and over three years, why isn't it implemented already!
Come on :joy_cat:
Please be constructive and specific; we do not need dozens of PLEASE DO IT ALREADY comments
But guys, please be specific also on your side.
Obviously community is very interested in that feature, and TS team does not give us any specifics about future of this one.
I personally completely agree with @armandn , recent releases of TS brings relatively rarely used features while something like this is being held.
If you don't plan to do it, just tell us. Else please let us know how community can help.