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 say please reopen! I'd be happy with a compiler option.
yes - please reopen
Reopen this!
Doesnt ES7 require this overriding/overloading multiple methods having same name? On Apr 8, 2016 10:56 AM, "Aram Taieb" [email protected] wrote:
Yes, please reopen this!
— 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-207466464
+1 - for me this is the largest gap in type safety that I have in day-to-day TypeScript development.
Every time I implement a React lifecycle method like "componentDidMount" I search for the relevant react documentation page and copy/paste the method name, to ensure that I don't have a typo. I do this because it takes 20 seconds whereas the bugs from a typo are indirect and subtle, and can take much longer to track down.
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.
If this is the major concern, call the keyword check_override to make clear that you're opting in to override checking, and by implication the others methods are not checked rather than not overridden.
What about using implements.? Being something like this:
class MyComponent extends React.Component<MyComponentProps, void>{
implements.componentWillMount(){
//do my stuff
}
}
This syntax has some advantages:
- It uses an already existing keyword.
- After writing
implements.the IDE has an excelent oportunity to show an autocompletion popup. - the keyword clarifies that can be used to force checking on abstract methods of base classes but also implemented interfaces.
- the syntax is ambiguous enough to be usable also for fields, like this:
class MyComponent<MyComponentProps, MyComponentState> {
implements.state = {/*auto-completion for MyComponentState here*/};
implements.componentWillMount(){
//do my stuff
}
}
Note: Alternatively we could use base., it's sorter and more intuitive, but maybe more confusing (defining or calling?) and the meaning is not so compatible with interface implementation. Example:
class MyComponent<MyComponentProps, MyComponentState> {
base.state = {/*auto-completion for MyComponentState here*/};
base.componentWillMount(){ //DEFINING
//do my stuff
base.componentWillMount(); //CALLING
//do other stuff
}
}
I don't think implements sufficiently covers all of the use cases
mentioned previously & it's a little ambiguous. It doesn't give any more
information to an IDE that override couldn't either, so it would seem to
make sense to stick with the terminology many other languages have used to
achieve the same thing.
On Wed, 13 Apr 2016 at 19:06, Olmo [email protected] wrote:
What about using implements.? Being something like this:
class MyComponent extends React.Component<MyComponentProps, void>{ implements.componentWillMount(){ //do my stuff } }
This syntax has some advantages:
- It uses an already existing keyword.
- After writing implements. the IDE has an excelent oportunity to show an autocompletion method.
- the keyword clarifies that can be used to force checking on abstract methods of base classes but also implemented interfaces.
- the syntax is ambiguous enough to be usable also for fields, like this:
class MyComponent<MyComponentProps, MyComponentState> { implements.state = {/auto-completion for MyComponentState here/};
implements.componentWillMount(){ //do my stuff }}
— 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-209571753
The problem with override is that once you use the same keyword you have the same expectations:
- it should be mandatory, at least if the method is
abstract. - you miss then some
virtualkeyword to annotate methods that are meant to be overridden but have default behavior.
I think the TS team doesn't want to add so much OO baggage to the language, and I think is a good idea.
By using implements. you have a lightweight syntax for getting the main benefits: auto-complete and compile-time checked name, without inventing new keywords or incrementing the concept count.
Also has the benefit of working for classes and interfaces, and for methods (in the prototype) or direct fields.
Ways of making override mandatory have already been discussed in the thread and the solutions aren't different to other features implemented by the compiler.
The virtual keyword doesn't really make sense in the context of the language and neither is it named in a way that is intuitive for people who haven't used languages like C++ before. Perhaps a better solution to provide this type of guard, if needed, would be the final keyword.
I agree language features should not be added hastily that could create 'baggage', but override plugs a legitimate hole in the inheritance system that many other languages have deemed necessary. It's functionality is best achieved with a new keyword, certainly when alternative approaches are to suggest fundamental syntax changes.
What about setting inherited fields vs redefining new ones? React state is a good example.
Or implementing optional interface methods?
override could potentially be used on fields, if they're being re-declared in the subclass body. Optional interface methods aren't overrides so are outside of the scope of what we're talking about here.
On Thu, 14 Apr 2016 at 11:58, Olmo [email protected] wrote:
What about setting inherited fields vs redefining new ones? React state is a good example.
Or implementing optional interface methods?
— 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-209879217
Optional interface methods aren't overrides so are outside of the scope of what we're talking about here.
Optional interface methods are a concept fairly unique to TypeScript as far as I know, and I think a TypeScript implementation of "overrides" should apply to them to.
In the case of React lifecycle methods like componentDidMount, these are optional interface methods that have no implementation in the superclass.
In the case of React lifecycle methods like componentDidMount, these are optional interface methods that have no implementation in the superclass.
Exactly, so they don't override anything. I think we're getting confused about what the override keyword is intended to provide here, because if you're just looking for a way of getting better code hinting/intellisense there are other ways that can be achieved without adding new keywords to the language.
Guys, with all due respect, can we please stay focused. I think that discussing alternative keywords is counterproductive, especially since the Issue was started with a specific request.
Can we all either agree that we need override and ask nicely the Typescript team to add it or drop the request and let the Issue closed?
I think it's always useful to pose the request in the context of what the problem is, there's always different ways to solve the problem. The sticking point with override was around it being mandatory or not (some making the point that it isn't mandatory in C++). The problem a lot of people have referenced is getting the name right for overridable functions (which may or may not be implemented in the super class) - React's lifecycle functions being the main problem.
If override doesn't work, then maybe we should close this issue and open a more general point about this problem. The general problem here is that the interface contract with a superclass is untyped and unchecked, and that's tripping up developers and it would be great if TS or the tooling can help.
@armandn I don't think our lack of closure or the niceness of our suggestion is what's keeping the request rejected, but the differences between C# and TS semantics:
C# base method override:
- Requires
overridekeyword - Creates a new record on VTable
- Checks for mandatory abstract/virtual in base method
- Checks for identical signature
- IDE: Triggers auto-complete after writing override
C# interface implementation:
- No keyword necessary, but explicit interface implementation possible using the interface name.
- Create a new interface record in the VTable.
- Checks for identical signature
- IDE: QuickFix for implement interface / implement interface explicitly.
So the behavior in C# are quite different depending if you ask about classes or interfaces, but in any case you get the main three benefits:
- Checking for identical signature
- Checking that the method can/should be overridden (misspelling in method name)
- IDE support writing the function
With slightly different semantics, we already have 1) in TS, unfortunately 2) and 3) are missing. The reason override was rejected, in my opinion, is that a similar syntax assumes a similar behavior, and this not desirable because:
A class with 5 methods, of which 3 are marked override, wouldn't imply that the other 2 aren't overrides.
It happens that we already have 1) 2) and 3) when writing object literals, but not when writing class members that extend other classes or implement interfaces.
With this in mind I think we can all agree on this semantics:
- The keyword should be ambiguous enough to avoid the 'split world' problem. (i.e.:
checkorsuper., orMyInterface.) - No checks for
abstract/virtualbut checks for member existence in the base class / implemented interfaces. (Benefit 2) - Checks for similar-enough signature compatibility as TS is doing so far. (Benefit 1)
- IDE: Triggers a auto-complete after the keyword. (Benefit 3)
Additionally, I think this two are necessary for completeness of the solution*:
- It should work for Classes and Interfaces, because TS is mainly interface based and classes are a shortcut for prototypical inheritance. Necessary considering optional interface methods.
- It should work for Methods and Fields, because methods are just functions residing in a field.
This two points are useful in the very-real use case of React component implementation:
class MyComponent<MyComponentProps, MyComponentState> {
implements.state = {/*auto-completion for MyComponentState here*/};
implements.componentWillMount(){
//do my stuff
}
}
The Annotation-based solution from @RyanCavanaugh is not enough because:
- It won't work with interfaces.
- It won't work with fields.
- Assuming a Roslyn-like infrastructure for helping with the tooling, there is no way to add a QuickFix after writing auto-complete list after writing
@override.
Given the semantics, it's just about choosing the right syntax. Here some alternatives:
override componentWillMount(): Intuitive but misleading.check componentWillMount(): Explicit but keyword-consuming.super componentWillMount():implements componentWillMount():super.componentWillMount():implements.componentWillMount():this.componentWillMount():ReactComponent.componentWillMount():
Opinions?
@olmobrutall good summary. Couple of points:
One keyword option (taken from C#) would be new - indicating a new slot:
class MyComp extends React.Component<IProps,IState> {
...
new componentWillMount() { ... }
componentWillMount() { ...} // would compile, maybe unless strict mode is enabled
new componentwillmount() { ... } <-- error
My other point is the issue with mandatory nature of using the above. As a contract between the parent super class and the derived class it makes sense to specify what are interface points where the above syntax would be valid. These are really internal extensions points for the super class, so something like:
class Component<P,S> {
extendable componentWillMount() {...}
}
The same would apply to the interface too.
Thanks :)
What about just writing this?
class MyComponent<MyComponentProps, MyComponentState> {
this.state = {/*auto-completion for MyComponentState here*/};
this.componentWillMount(){
//do my stuff
}
}
About extendable, there's already abstract in TS 1.6, and adding virtual will maybe create again the split world problem?
Right, I thought about abstract but there may be an implementation in the super class, so it doesn't really make sense. Likewise with virtual, as that would imply non-virtual members are not virtual - which is misleading.
this. works, I guess you could even have (as a long form):
this.componentWillMount = () => { }
The only issue with this is that it should only be scoped to earmarked extension points, not all members of the base class.
what is going on...
TypeScript isn't and never has been the javascript version of C#. So the reason isn't because the suggested functionality differs from the semantics of C#. The reasons for closure as stated by Ryan and then clarified by Daniel R were
As Ryan explained, the issue is that marking a method as an override doesn't imply that another method isn't an override. The only way that it would make sense is if all overrides needed to be marked with an override keyword (which if we mandated, would be a breaking change).
Yet you're still persisting with your problems around autocomplete. Autocomplete doesn't need a new keyword in the language to provide you with improved suggestions.
The reason this thread exists was to get compiler errors when a function is illegally overridden or when a method was declared to be an override but didn't actually override a function in a base class. It's a simple and well defined concept across many languages that also support most if not more language features typescript has to offer. It doesn't need to solve all the worlds problems, it just needs to be the override keyword, for overrides.
More people have since shown interest in the original proposal, so lets stick to the topic the issue was raised for and raise new issues for new ideas.