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 not sure how you apply this to fields in a way that makes sense.
We're talking about adding a keyword that is only applicable in the class body, yet fields can be reassigned at any point during the instances lifetime.
Typescript already allows you to initialize fields in the class body:
class Person {
dateOfBirth : new Date();
}
It also allows you to re-initialize fields declared in the parent class, but the situation bad. Of course you could write the name wrongly (similar problem to override) but the type is also erased. This means that:
class Person {
fullName: { firstName: string; lastName?: string };
}
class SuperMan extends Person {
fullName = { firstName: "Clark" };
bla() {
this.fullName.lastName; //Error
}
}
This code fails with: Property 'lastName' does not exist on type '{ firstName: string; }'. because the original type has been erased!.
We're talking about adding a keyword that is only applicable in the class body, yet fields can be reassigned at any point during the instances lifetime.
Also methods:
class Person {
talk() { }
}
class SuperMan extends Person {
talk() { }
changeMe(){
this.talk = () => { };
}
changeMyPrototype() {
SuperMan.prototype.talk = () => { };
}
}
@kungfusheep I agree, fields can be reassigned, but so do methods on the prototype. The main reason why we would need a keyword for "overriding" fields is because instance methods are fields and they're widely used instead of proper prototype methods because they're lambdas and thus autobind the context.
@olmobrutall
About overriding methods with fields
It's forbidden and with good reason I believe (it's not the same thing so it shouldn't be compatible), but you're right that it's possible to do so when directly manipulating the instance of the class. I don't know exactly why it is allowed, but we're not here to change how the language works so I believe we shouldn't interfere here.
About interfaces
Class interfaces describe the instance side of a class, meaning fields as well as methods from the prototype. I don't even think there's a difference between instance and prototype methods in an interface, I believe you can describe a method as one or the other, and implement it as one or the other. So implement could (and should) also apply to fields.
About new
new should have the same semantics as override does, so obviously you can't change the type to something that isn't compatible. I mean, again, we're not changing how the language works. I just wanted a separate keyword because it's not the same kind of redefinition. But, I agree that, as you showed me, we can already tell fields and methods apart by the use of =, so maybe the same keyword/syntax could be used were without ambiguity.
About this.
However, the unified field/method override syntax shouldn't be this.method() or this.field because it looks a lot like something that could be valid Javascript, while it's not. Adding a keyword before the member would be clearer towards the fact that is indeed a Typescript thing.
this is a fine idea though, so maybe we could drop the dot and write something less ambiguous like
class Superman {
this walk() { }
}
But still, it looks a but weird. And mixing it with implement would look a bit out of place (because we're okay with the fact that this this syntax wouldn't be used with interface?), and I like the implement/override duo. An override modifier on fields still irks me, but maybe it is better that having a third ambiguous new keyword. Since the assignation (=) makes the difference between a method and a field clear, that would be fine by me now (as opposed to what I was saying a few hours ago).
I agree, fields can be reassigned, but so do methods on the prototype.
Yeah, modifying the prototype directly, in TypeScript, is very much in the realms off messing around under the hood though. It's nowhere near as common as simply re-assigning a property on an instance of something. We very rarely use fields as functions, over a 150k+ line codebase, so I think to say it's widely used is maybe subjective.
I agree with most of your other points, but I'm not sold (and by the sound of it, neither are you...) about the use of the new keyword in this context.
We very rarely use fields as functions, over a 150k+ line codebase, so I think to say it's widely used is maybe subjective.
I don't either, but I have to resort to an @autobind decorator to properly bind this in my methods, which is more cumbersome than simply writing a lambda instead. And as long as you don't use inheritance, using a field works like you expect. I was under the impression that, at least in the JS/React world, most people using ES6 classes were using arrow functions as methods.
And interface methods can be implemented either with a proper method or with an instance method, which does not help with clarifying the difference.
I believe fields have the same problems as methods as far as overrides are concerned.
class A {
firstName: string;
get name() {
return this.firstName;
}
}
class B extends A {
firstname = "Joe" // oops
}
A possible workaround here is to assign the field in the constructor
class B extends A {
constructor() {
this.firstName = "Joe"; // can't go wrong
}
}
but that's not applicable for interfaces. That why I (and others here) believe we need something to check the pre-existence of a field when declaring it directly in the class body. And it's not an override. Now that I put some more thoughts here, I believe the issue with fields is exactly the same as the issue with interface members. I'd say we need an override keyword for methods that already have an implementation in a parent class (prototype methods, and maybe instance methods too), and another for things that are defined but without implementation (non-function fields included).
My new proposition would be, and using a tentative member keyword (probably not the best choice):
interface IBase {
interfaceField?: string;
interfaceMethod(): void
}
abstract class Base {
baseField: number;
baseMethod() { }
baseLambda: () => { };
abstract baseAbstractMethod();
}
class Derived extends Base implements IBase {
member interfaceField = "Hello";
member interfaceMethod() { }
member baseField = 2;
override baseMethod() { }
override baseLambda = () => { };
member baseAbstractMethod() { }
}
Note that I would choose the member keyword for an abstract method since I said override would be for things with an implementation, indicating that we're replacing an existing behavior. Instance methods would need to use override by virtue of being a special kind of field (which is already recognized as such by the compiler since method signatures can be implemented with it).
I think that Typescript should be a compile-time checked version of JavaScript, and by learning TS you should be learning JS as well, just as by learning C# you get a good intuition of the CLR.
Prototypal inheritance is a cool concept of JS, and a quite central one, and TS should not try to hide it with concepts from other languages that do not make too much sense here.
Prototypal inheritance doesn't make any difference if you're inheriting methods or fields.
For example:
class Rectangle {
x: number;
y: number;
color: string;
}
Rectangle.prototype.color = "black";
Here we are setting a simple field in the prototype object, so all the rectangles will be black by default without having to have a instance field for it.
class BoundingBox {
override color = "transparent"; // or should be member?
}
Also the member keyword makes the other members in the class jealous.
What we need is a syntax that will allow in a class declaration context the same kind of behavior (compile time checked/auto-complete/renames) that we already have in object literal or member expressions.
Maybe a better alternative to this. is just .:
class Derived {
.interfaceField = "hello";
.interfaceMethod() {}
.baseField = 2;
.baseMethod() {}
.baseLambda = () => {};
.baseAbstractMethod(){};
someNewMethod(){}
someNewField = 3;
}
In conclussion, I don't think the the Typesystem shouod track which values come from the prototype and which from the instance, because this is a hard problem once you can access the prototype imperatively, and because is not going to fix any problem while will limit the expressivity of JS.
So there is no difference between a function field, and arrow function field and a method, nor in the type system, nor in the generated code (if this is not used).
Hey guys, this is interesting stuff, but it's pretty out on a tangent in terms of override specifically. I'd be happy to have some new Discussion issue for this kind of thing to go in unless we can link these comments back to the original suggestion more concretely.
A lot of what you're saying here is really not specific to TypeScript, either, so starting an ESDiscuss thread may also be appropriate. Certainly they've thought about this sort of thing just as much (in terms of what goes on the prototype vs the instance).
@olmobrutall ES6 classes are already hiding the prototype stuff, and like @kungfusheep said, messing directly with it isn't exactly a normal thing to do.
So there is no difference between a function field, and arrow function field and a method, nor in the type system, nor in the generated code (if this is not used).
Well, in the generated code, class methods are put in the prototype and everything else (not prefixed with static) in put in the instance, which does make a difference with inheritance.
Anyway, I now agree that we don't have to have a separate syntax for both kinds of methods, but if we were to use the override keyword, it should be limited to methods and we'd have to find something else for the rest. Having a unique keyword for everything could be nice but it should be very clear about its meaning. override is clear, but only for methods. You dot syntax, this like this. is still too close to existing JS to my taste.
@RyanCavanaugh
It's preatty out of tangent in terms of
override
My issues with override is that is not general enough for interface methods and fields. I see three options:
- use
overridejust for base class methods. - use
overridefor interface methods and fields as well - consider alternative syntaxes (
member,implement,this.,., etc...) - do nothing (that will be sad)
I think this decision should be taken here.
A lot of what you're saying is really not specific to Typescript
Absolutely! we are all happy about the current state for transpiling, but not on the type-checking / tooling.
Whatever the keyword is, it will be Typescript only (just as abstract)
@JabX
You right about the generated code, of course. My point was that you can write something like this:
class Person {
name: string = "John";
saySomething() {
return "Hi " + this.name;
}
}
We declare a class, name will go to the instance while saySomething to the prototype. Still I can write this:
Person.prototype.name = "Unknown";
Because the type of Person.prototype is the whole person. Typescript doesn't keep track of what goes where on his type system for simplicity.
Having a unique keyword for everything could be nice but it should be very clear about its meaning.
What I think is more important and we all could agree is the semantics:
Modified XXX checks that the member is already declared in the base class or implemented interfaces, typically used to override functions from the base class.
Since . or this. look too alien, and member is redundant, I think probably the best choice is to abuse override for all the cases. Setting fields or implementing interface methods is anyway a side-feature.
There are many precedents:
- In C# an
static classis not really a class of objects anymore. - There is nothing static about
staticfields. virtualmethods are quite concrete (VB usesOverrideable).
It will look like this:
class Person{
dateOfBirth: Date;
abstract talk();
walk(){ //...}
}
interface ICanFly{
fly?();
altitude?: number;
}
class SuperMan extends Person implements ICanFly {
override dateOfBirth = new Date();
override talk(){/*...*/}
override walk = () => {/* force 'this' to be captured*/}
override fly() {/*...*/}
override altitude = 1000;
}
Can we settle on that?
I'd rather see a separate implement keyword for anything that comes from interfaces (with priority to override if it's in both), because it's what it is: an implementation, not an override.
Otherwise, I agree it might be best to abuse override for everything from the parent class.
But there's no semantic difference between implement and override.
Both are going to have similar auto-complete / error messages / transpilation to JS... it's just a philosophical difference.
It's really worth to explain two keywords and that a pedanting compiler tells you: Error you should use 'override' instead of 'implement'.
What about a this case:
interface IComparable {
compare(): number;
}
class BaseClass implements IComparable {
implement compare();
}
class ChildClass extends BaseClass implements IComparable { //again
override compare(); // or implements...
}
The questions is... who cares?.
Also there is the implement/implements issue.
Let's just abuse override. One concept one keyword, this is the important thing.
Well, I already proposed that override should have priority over implement, but I probably wasn't clear enough.
I still don't believe this is the same thing. Another example: for a mandatory interface member, a failure to implement is a compiler error whereas a failure to override is not an issue (unless the base member is abstract that is...).
I just don't think that override on something that isn't declared on a parent class would make any sense. But maybe I'm the only one who wants the distinction. In any case, whatever keyword we end up using for this, I just hope we can settle on something and provide a strict mode to enforce its use.
Well, I already proposed that override should have priority over implement, but I probably wasn't clear enough.
Sure, I just wanted to say that there are four cases. Base Class, Interface, Interface in Base Class, Re-implement Interface in BaseClass.
@JabX
I just don't think that override on something that isn't declared on a parent class would make any sense. But maybe I'm the only one who wants the distinction.
You're not. They are two fundamentally different things and there is benefit in having that separation at language level.
I think if interfaces are to be supported in this new functionality then it cant be some half-baked solution that's been bolted onto override. For the same reason extends exists as a separate entity to implements at class level, override needs to be paired with something along the lines of implement in order to fix this problem. It's replacing functionality vs defining functionality.
@olmobrutall
It's really worth to explain two keywords and that a pedanting compiler tells you: Error you should use 'override' instead of 'implement'.
I feel like I've made this distinction about 4 times now, but this isn't pedantic; it's really important information!
Consider your own example
interface IComparable {
compare(): number;
}
class BaseClass implements IComparable {
implement compare();
}
class ChildClass extends BaseClass implements IComparable { //again
override compare(); // or implements...
}
'or implements...' is a totally incorrect assumption to make in this case. Just because you've told the compiler you want to implement the same interface as the base class you're extending doesn't change the fact that you've already implemented compare.
If you were to write implement in ChildClass instead of override then you should be thankful that the compiler would then tell you of your incorrect assumption, because it's a big deal that you were about to unknowingly wipe out a previously implemented method!
In the codebases that I'm responsible for this would be a big problem without a doubt; so I welcome any compiler feature that can prevent any such developer mistakes!
@kungfusheep
If you were to write implement in ChildClass instead of override then you should be thankful that the compiler would then tell you of your incorrect assumption, because it's a big deal that you were about to unknowingly wipe out a previously implemented method!
If overriding an already implemented method is such an important decision then implement should be used for abstract methods as well. If you change a method from abstract to virtual or the other way around you should check (and change) all the implemented versions to consider calling super or just removing the method.
In practice this has never been an issue in C#.
I agree, override for implemented methods, and implements for unimplemented methods (abstract / interface).
It could be used for abstract, yes.
In C# there wasn't the 'optional' interface scenario, so perhaps wasn't deemed as much of an issue.
But my point is that in C# we override implemented and unimplemented methods and I've never heard of someone complaining.
I don't think is really an issue that deserves making explaining the feature at least two times harder.
Well, the only reason why we need an implement keyword is because interface members can be optional, whereas it's not possible in C# (and probably in most OO languages too). There is no keyword for that there because you cannot not implement an interface completely, so no issue. Don't base your argument on "it's the same in C#" too much, because we have different problematics here.
override is used for base class methods, whether they're abstract or not. I suppose we should to the same (override instead of implement for abstract methods) here because I believe the distinction should be on the origin of the method (class or interface) instead of on the existence of the implementation. And in the future, if you decide to give a default implementation to your abstract method, you won't have to go through your code (or worse, to the code of others using your class) to replace the keywords.
My main question now is, should we have a strict override/implement flag (I totally want this), should we force the implement keyword on mandatory interface members? Because it doesn't help a lot (you can't fail to implement these because otherwise it won't compile) and could lead to a lot of unnecessary verbosity. But on the other hand, it might be deceiving to have the implement on some interface members but not on all of them.