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.
TypeScript isn't and never has been the javascript version of C#.
I'm comparing it with C# as a reference language, since I assume this is the behavior you guys are assuming.
Autocomplete doesn't need a new keyword in the language to provide you with improved suggestions.
How you suggest it to be triggered then? If you show a autocomplete combobox when writing a random name in a class context will be very annoying when we just want to declare a new field or method.
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.
I absolutely included this use case, under Benefit 2.
It doesn't need to solve all the worlds problems, it just needs to be the override keyword, for overrides.
So your suggestion is to fix one step at a time instead of moving one step back and look at similar/related problems?. That maybe a good idea for your Scrum Board but not for designing languages.
The reason they are conservative about adding the keyword is that they can not remove features from a language.
Some design mistakes in C# because of lack of completion:
- Unsafe Array co-variance / contra-variance.
varonly working for variable types, not for automatic generic parameters or return types. Maybleautowill be a better keyword like in C++?
Just try to use React for a second and you'll see the other side of the picture.
Overriding a method that's already been implemented in a base class and implementing an interface method are two completely different things. So yes, what's being suggested is to fix one of those scenarios with a dedicated keyword instead of trying to come up with some Swiss-Army keyword.
What good is a keyword that can mean any one of 3 different things to developers reading some code for the first time? It's ambiguous and confusing, especially if you're talking about using a keyword like this which already does other (totally unrelated!) things in the language - it couldn't be more generic, it's almost useless.
If your main concern is auto-complete, editors have enough information now to be able to suggest methods from base classes and implemented interfaces 'as you type'.
Overriding a method that's already been implemented in a base class and implementing an interface method are two completely different things.
In the general case yes, but we're not talking about implementing any interface method. We're talking about an optional interface method where the parent class implements the interface. In this case you can say that 1) interface permits the method to be implemented as undefined, 2) the parent class has an undefined implementation, and 3) the child class is overriding the undefined implementation with a method implementation.
@olmobrutall I think your comment about designing languages and how it is not a scrum board is a little self-serving. I have seen about four updates to TS in the space of under a year.
If the language design was as well considered as you imply it should be, then there would already be a language spec document telling us exactly how overrides should work, and we mightn't even be having this conversation.
I don't make this comment with any denigration of the TS developers/designers, because TS is already excellent and I would dread having to use standard JS instead.
Yes TS is not C# and it's not C++. But a number of languages have chosen the override keyword to meet the objectives discussed here so it seems counterproductive to suggest totally alien syntax.
The chief issue seems to be not wanting to introduce a breaking change. The simple answer is a compiler flag, end of story. For some people like me, an optional override keyword is useless. For others they want to embellish their code incrementally. Compiler flag solves the dilemma.
Signature differences are a different conversation. The new keyword appears unnecessary because JS can't support multiple methods of the same name (unless TS creates signature-derived mangled names a'la C++, which is highly unlikely).
I have seen about four updates to TS in the space of under a year.
I don't mean you can not be fast and iterate quickly. I'm as happy as anybody that ES6 and TS are evolving fast. What I mean is that you have to try to predict the future, to avoid putting the language in a dead end.
I could agree on using override keyword. With proper arguments even keeping fields and interfaces out of the scope, but I can not agree with the 'let's stay focused and solve just this particular problem the way other languages do it without thinking too much' argument.
But a number of languages have chosen the override keyword to meet the objectives discussed here so it seems counterproductive to suggest totally alien syntax.
None of this languages have prototypal inheritance or optional method (methods that are neither abstract or virtual, they just could not exist at runtime), and this are related problems that have to be discussed (and maybe discarded) before making a commitment.
Put another way: let's say we do as you seem to suggest and we implement override without thinking to much. Then me, or anybody else using TSX, adds an issue with why override doesn't work with React components. Whats your plan?
In the general case yes, but we're not talking about implementing any interface method. We're talking about an optional interface method where the parent class implements the interface.
It doesn't matter where the interface was set up, the fact is they are not the same thing and so shouldn't share a keyword because the intent of the program is not clear.
You could, for example, be overriding a method which had been implemented for interface compliance in a base class; If we were to put all our eggs in one keyword for these two different things, how would anyone then know if this was the initial declaration of that function or an override to one previously defined in a base class? You wouldn't, and it wouldn't be possible to know without further inspection of the base class - which may even be in a 3rd party .d.ts file & thus making it an absolute nightmare to find, depending how deep in the inheritance chain the function was originally implemented.
Put another way: let's say we do as you seem to suggest and we implement override without thinking to much. Then me, or anybody else using TSX, adds an issue with why override doesn't work with React components. Whats your plan?
Why does this need to fix React? If React has a different problem to what this is trying to solve then I can't for the life of me fathom why override needs to fix it? Have you tried opening another issue to suggest something be done about interface implementation?
I wouldn't agree that enough thought hasn't been put in to this. We're suggesting a tried and tested technique that's been successful in every other language I can think of that's implemented it.
the fact is they are not the same thing and so shouldn't share a keyword because the intent of the program is not clear.
Are not? Look at this two alternative definitions of BaseClass
class BaseClass {
abstract myMethod();
}
interface ISomeInterface {
myMethod?();
}
class BaseClass extends ISomeInterface {
}
And then in your code you do:
class ConcreteClass {
override myMethod() {
// Do stuff
}
}
You think it should work in just one case and not in the other? The effect is going to be 100% identical in Javascript (creating a new method in ConcreteClass prototype), from the external interface and from the tooling perspective.
Even more, maybe you want to capture this inside of the method, implementing it with a lambda (useful for React event handling). In this case you'll write something like this:
class ConcreteClass {
override myMethod = () => {
// Do stuff
}
}
The behavior will be again identical if the method is abstract or comes from the interface: add a field in the class with a lambda implementing it. But it looks a little bit strange to override a field, since you're just assigning a value.
Not let's see it using super. (my favorite syntax right now, but I'm open to alternatives).
class ConcreteClass {
super.myMethod() { //method in prototype
// Do stuff
}
super.myMethod = () => { //method in lambda
// Do stuff
}
}
Now the concept is conceptually simpler: My super class says that there is a method or field and the ConcreteClass can define it in the prototype / assign it / read it / call it.
Why does this need to fix React?
Is not just react, look at angular:
Of course most of the interfaces are not meant to be implemented, neither all the classes to be overriden, but one thing is clear: in Typescript interfaces are more important than classes.
Have you tried opening another issue to suggest something be done about interface implementation?
How should I call it? override for interface and fields?
We're suggesting a tried and tested technique that's been successful in every other language I can think of.
The languages you have in mind are quite different. They have inheritance based in a static VTable.
In Typescript a class is just an interface + automatic prototype inheritance of methods. And methods are just fields with a function inside.
In order to adapt the override feature to TS this two fundamental differences have to be considered.
Please @kungfusheep make the effort to think about a solution to my problem. If you want to add different keywords and implement them in a second stage is O.K., but take a second to imagine how it should be.
I can't think of another way to say what I've already said. They are not the same. They are similar, but not the same. Please see this comment by one of the TS devs RE: the readonly keyword - https://github.com/Microsoft/TypeScript/pull/6532#issuecomment-179563753 - which strengthens what I'm saying.
I agree with the general idea, but let's see in practice:
class MyComponent extends React.Component<{ prop : number }, { value: string; }> {
//assign a field defined in the base class without re-defining it (you want type-checking)
assign state = { value : number};
//optional method defined in an interface implemented by the base class
implement componentDidMount(){
}
//abstract method defined in the base class
override render(){
}
}
This looks like VB or Cobol, doesn't it?
It looks like it makes sense, at least.
Consider this example, were there only the override (or just one) keyword.
interface IDo {
do?() : void;
}
class Component implements IDo {
protected commitState() : void {
/// do something
}
override public do() : void {
/// base implements 'do' in this case
}
}
Now lets implement our own component using what we just wrote.
class MyComponent extends Component {
override protected commitState(){
/// do our own thing here
super.commitState();
}
override do() : void {
/// this is ambiguous. Am I implementing this from an interface or overriding a base method? I have no way of knowing.
}
}
One way of knowing would be the type of super:
override do() : void {
super.do(); // this compiles, if it was an interface then super wouldn't support `do`
}
exactly! which means the design is wrong. there shouldn't be an investigation involved with skimming code, it should just make sense when you read it.
this is ambiguous. Am I implementing this from an interface or overriding a base method? I have no way of knowing.
What's the difference in practice? The object has just one space of names and you can only place one lambda in the do field. There's no way of explicitly implementing an interface anyway. The implementation is going to be:
MyComponent.prototype.do = function (){
//your stuff
}
independently of what you write.
It doesn't matter what the output is. You could be either intentionally or unintentionally overriding some functionality in a base class, but there is no intent in a keyword that is ambiguous.
What error or unexpected behavior will be solved by having two keywords?
Come on now mate. You're obviously a clever guy. I've just said "unintentionally overriding some functionality in a base class"; can we not infer from this any unexpected behaviour that could have potentially just occurred?
To be clear, I'm not proposing turning this issue into a proposal for two keywords. This issue is for the override keyword - anything else will need a new proposal and its own discussion on semantics.
To be clear, I'm not proposing turning this issue into a proposal for two keywords. This issue is for the override keyword - anything else will need a new proposal and its own discussion on semantics.
It doesn't really matter in how many issues it should be discussed, or from whom the idea comes. You propose to split two very related thinks and don't even consider a consistent syntax.
The arguments for whether we need 1, 2 or 3 keywords belong to this thread and is not finished (...but becoming repetitive). Then maybe we can discuss the syntax in another thread (because the semantics are going to be identical anyway :P).
In my example:
class MyComponent extends React.Component<{ prop : number }, { value: string; }> {
//assign a field defined in the base class without re-defining it (you want type-checking)
assign state = { value : number};
//optional method defined in an interface implemented by the base class
implement componentDidMount(){
}
//abstract method defined in the base class
override render(){
}
}
Don't assign, implement and override do exactly the same thing: Check that the name exist (in the base class, the implemented interfaces, the interfaces implemented by the base class, etc...).
If there's a name conflict between base classes and some implemented interfaces you'll get an compile-time error whether with 1, 2 or no keyword at all.
Also think about the object literal:
var mc = new MyComponent();
mc.state = null;
mc.componentDidMount =null;
mc.render = null;
With exactly the same syntax I can re-assign fields or method independently if they come from the base class, direct interface implementations or interfaces implemented in the base class.
Don't assign, implement and override do exactly the same thing: Check that the name exist (in the base class, the implemented interfaces, the interfaces implemented by the base class, etc...).
You've just described 3 different scenarios there, so obviously they're not the same. I have a feeling I could describe why they're different to you all day and you'd still be sat arguing that they're not, so I'm going to bow out of this particular line of discussion for now. There's nothing to say the TS guys are still considering this at the moment anyway.
With the closure of #6118 I think there's reason to discuss if the problems there and the problems here can be addressed simultaneously.