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.
https://github.com/Microsoft/TypeScript/pull/24626 too.
Just a timeline here since there are more comments than GitHub is willing to display on load:
- The initial issue was opened
- We reviewed it and declined it on complexity vs value grounds https://github.com/Microsoft/TypeScript/issues/2000#issuecomment-98874744
- We reopened it after #6118 failed to work https://github.com/Microsoft/TypeScript/issues/2000#issuecomment-216626012
- We said we'd accept a PR after making some decisions https://github.com/Microsoft/TypeScript/issues/2000#issuecomment-224776519
- PR got opened at #13217
- After extensive review of the PR (nearly 100 comments) we took it back to the design meeting due to complexity concerns #20724
- Again, we decided that the benefits of the feature did not outweigh complexity
It's not like we're not taking consideration here. This is as close as features get to going in, and we've rejected our own feature ideas on similar grounds - see #24423 for a recent example.
We really want to grow the language intentionally. This takes time, and you should expect to have to be patient. By comparison, C++ is older than a lot of people in this thread; TypeScript is not yet old enough to be at home without adult supervision. Once we add something to the language, we can't take it out again, so every addition has to be carefully weighed against its pros and cons. I speak from experience that features people were SCREAMING for (extension methods, I'm looking at you) would have destroyed our ability to continue evolving the language (no intersection types, no union types, no conditional types) had we implemented them just because there were lots of GitHub comments. I'm not saying override is a dangerous thing to add, just that we are always approaching this with the absolute maximum of caution.
If I had to summarize the core problems with override right now:
- It doesn't let you do anything that you can't do today with a decorator (so it's "not new" in terms of "things you can accomplish")
- The semantics cant't precisely align with
overridein other languages (increases cognitive load) - It doesn't "light up" 100% without a new commandline flag, and it'd be a flag we'd probably want to be under
strictbut realistically couldn't because it'd be too big of a breaking change (decreases delivered value). And anything that implies a new commandline flag is another doubling of the configuration space that we need to weigh seriously, because you can only double something so many times before it consumes your entire mental budget when making future decisions - Fairly strong internal disagreement here about whether
overridecan apply to implementing an interface member (decreases perceived value because expectations won't match reality for some proportion of people)
The total upside here is that you can a) indicate that you're overriding something (which you could do today with a comment), b) catch a misspelling that autocomplete should have helped you with anyway, and c) with a new flag, catch places where you "forgot" to put a keyword and now need to (a plain mechanical task that is unlikely to find real bugs). I get that b) is extremely frustrating but again, we need to meet the complexity bar here.
At the end of the day if you think JS classes would be enormously helped by an override keyword, then championing a TC39 proposal to add it to the core runtime would be a good place to start.
It doesn't let you do anything that you can't do today with a decorator (so it's "not new" in terms of "things you can accomplish")
Maybe I'm misunderstanding this, but there are pretty important things that a decorator can't do which the keyword could. I mentioned some in https://github.com/Microsoft/TypeScript/issues/2000#issuecomment-389393397. Definitely correct me if those things are possible, because I would like to use the decorator approach but non-abstract methods are only a small part of my use case for this feature.
Another upside not mentioned is that an override keyword would make changing something in a base class a lot more feasible. Changing a name or splitting something into two parts etc. is difficult knowing that any deriving classes will compile just fine without being updated to match but will probably fail at runtime. Also, considering that there's no final/sealed/internal keywords available, just about any exported class might be derived somewhere making changing just about anything non-private a lot riskier than it would be with override available.
My impression is that a TSLint rule would be by far the smoothest path forward here. @kungfusheep briefly mentioned the idea in https://github.com/Microsoft/TypeScript/issues/2000#issuecomment-192502734 , but I don't see any follow-up. Is anyone else aware of a TSLint implementation of this feature? If not, I'll probably start hacking on one when I get a chance. 😄
My current thought is it'll just be a comment, // @override, just like // @ts-ignore and various other comment-based directives I've seen. I'd personally prefer to shy away from decorators since (in their current form) they have runtime semantics and since they're still stage 2 and disabled by default.
With any luck, a custom TSLint rule would be a 90% solution, only really lacking in aesthetics, and of course it could move forward without having to commit to any details of the language. With type-aware rules, tslint-language-service, and auto-fixing, there's really not much difference between a TSLint error and a built-in TS error from the developer's perspective. My hope is that a TSLint plugin (or multiple competing plugins) would give the community some experience and a chance to come to more of an agreement on the best semantics. Then maybe it could get added as a core TSLint rule, and maybe that would provide enough clarity and motivation to justify the aesthetic benefit of an override keyword in the core language.
Just thinking outside the box here. We have two different scenarios here. C# (just as an example) uses virtual and override because methods are NOT virtual by default. In JavaScript all functions on a class are virtual by default (by nature). Does it not make more sense then to invert the process and have a nooverride type modifier instead? Of course people could still force it, but at least it’s there to help push a convention that some functions in base classes should not be touched. Again, just thinking outside the norm here. ;) It may also be less of a breaking change.
Does it not make more sense then to invert the process and have a
nooverridetype modifier instead?
I like your way of thinking, and I think what you are looking for is final.
What about readonly though? I believe overriding a method in JS actually means replacing the parent's with the child's during instantiation (when the prototype chain gets applied). In that case, having a readonly method to mean "It's there for everyone to see, but I don't want anyone to change it, whether by inheritance or dynamically after instantiation" makes a lot of sense. It's already implemented for members, why not do it for methods as well?
Is there already a proposal for it? If not it could be worth investigating as an alternative to override...
edit: turns out you can override a readonly member, so this whole argument collapses.
Perhaps allowing private class functions is another option?
Edit: I was thinking "instead of marking it final" but I must have been half asleep (obviously "final" means public but cannot override), LOL; nevermind.
@rjamesnw you can already define class functions as public, protected, private.
I don't think that only having "final" would be a solution. The problem is that people can accidentally create a new function in a class that inherits from a base class with that name already in use, and then you'll be breaking things silently without knowing why. It's happened to me a few times, very frustrating, as you often don't get errors, and strange things just happen (or don't)...
So I think, really, we're looking at a new tsconfig.json entry that will force the compiler to throw an error when something is overridden without it being marked as virtual (and the overriding one being marked as override or final).
I think that without override, TypeScript is disappointing its users on its [perceived] promise of compile-time safety and type-safety.
The "use an IDE command to override method" argument breaks down as the code is evolving (as other people have pointed out).
Also looks like all major comparable languages have added override in some form.
To not make it a breaking change, it could be a tslint rule (similarly as in Java).
Btw, why not allow breaking changes between major versions language e.g. 2.x -> 3.x. We don't want to get stuck, do we?
If it turns out something is wrong with certain details of override, and it requires some breaking-change-tweaking in 3.x, so be it. I think most people will understand and appreciate the tradeoff of evolution speed vs compatibility. Really without override I cannot recommend TS as something more practical than Java or C#...
If people want to be strict, there should be some way of mandatory override (could be an optional tslint rule). The value of mandatory override though is much lower, because chance of accidentally overriding a method from superclass seems much much lower than accidentally not-overriding.
Really this issue being open since 2015 is a bucket of cold water on my TypeScript enthusiasm and evangelism...
This does not handle overriding methods from grand*-parents:
function override(container, key, other1) {
var baseType = Object.getPrototypeOf(container);
if(typeof baseType[key] !== 'function') {
throw new Error('Method ' + key + ' of ' + container.constructor.name + ' does not override any base class method');
}
}
It is also sad and disappointing that No one assigned on GH here on this issue. Maybe time for a TypeScript fork? ;) CompileTimeSafeScript...
This whole thread looks like a big "Paralysis by analysis" anti-pattern. Why not just do the "80% cases value with 20% of work" and, try it in practice, and, if necessary, tweak it in 3.x ?
The simple, frequent and very valuable use cases are held "hostage" by some corner cases that most people will never really need to worry about.
So, this is possible to type-check at compile time via decorators, albeit not without a little bit of help:
export const override = <P extends Function>() => <K extends keyof P["prototype"]>(
target: Object,
methodName: K,
descriptor: TypedPropertyDescriptor<P["prototype"][K]>
) => {
// this is a no-op. The checking is all performed at compile-time, so runtime checks are not needed.
}
class Bar {
biz (): boolean {
return true;
}
qux (): string {
return "hi";
}
}
class Foo extends Bar {
// this is fine
@override<typeof Bar>()
biz (): boolean {
return false;
}
// error: type '() => number' is not assignable to type '() => boolean'
@override<typeof Bar>()
biz (): number {
return 5;
}
// error: argument of type '"baz"' is not assignable to parameter of type '"biz" | "qux"'
@override<typeof Bar>()
baz (): boolean {
return false;
}
}
I'm not sure if it's possible to get a reference to the super type without passing it in explicitly. This incurs a tiny runtime cost, but the checking is all compile time.
@alangpierce
My impression is that a TSLint rule would be by far the smoothest path forward here.
[...]
Then maybe it could get added as a core TSLint rule, and maybe that would provide enough clarity and motivation to justify the aesthetic benefit of an override keyword in the core language.
100% agreed. Let's get started already!
Hi - a little later than planned but here is our tslint rule implemented using a decorator.
https://github.com/bet365/override-linting-rule
We have been using this across our ~1mloc TypeScript codebase for a couple of years and have recently updated it to use the language service, making it much faster to execute and more feasible to open source (the previous iteration required a full pass of the project to gather the heritage information).
For our use-case it has been invaluable - though we're still of the opinion that the responsibility should ultimately lie with the compiler and as such the linting rule should be seen as a stop-gap.
Thanks
I agree. I also believe that a solution involving the TS compiler would be much better than decorators and lint rules.
What is the status of this feature? Has it been revisited as a compiler-feature yet?
So, this is possible to type-check at compile time via decorators, albeit not without a little bit of help:
Some improvements:
function override< Sup >( sup : { prototype : Sup } ) {
return <
Field extends keyof Sup ,
Proto extends { [ key in Field ] : Sup[ Field ] } ,
>(
proto : Proto ,
field : Field ,
descr : TypedPropertyDescriptor< Sup[ Field ] > ,
)=> {}
}
class Foo {
bar( a : number ) {
return a
}
bar2( a : number , b : number ) {
return a
}
}
class Foo2 {
@override( Foo )
bar( a : number ) {
return 1
}
@override( Foo )
bar2( a : number , b : number ) {
return 1
}
xxx() { return '777' }
}
class Foo3 extends Foo2 {
@override( Foo ) // OK
bar( a : number ) { return 5 }
@override( Foo ) // Error: less args than should
bar2( a : number ) { return 5 }
@override( Foo ) // Error: accidental override Foo2
xxx() { return '666' }
@override( Foo ) // Error: override of absent method
yyy() { return 0 }
}
Ok, found out override solution that prevents compilation error. Example with Node Readable stream:
// Interface so you will keep typings for all Readable methods/properties that are not overriden:
// Fileds that are `Omit`-ed should be overriden (with any signature you want, it do not have to be compatible with parent class)
interface ReadableObjStream<T> extends Omit<stream.Readable, 'push' | 'read'> {}
// Use extends (TYPE as any) to avoid compilation errors and override `Omit`-ted methods
class ReadableObjStream<T> extends (stream.Readable as any) {
constructor() {
super({objectMode: true}); // force object mode. You can merge it with original options
}
// Override `Omit`-ed methods with YOUR CUSTOM SIGNATURE (can be non-comatible with parent):
push(myOwnNonCompatibleSignature: T): string { /* implementation*/ };
read(options_nonCompatibleSignature: {opts: keyof T} ): string { /* implementation*/ }
}
let typedReadable = new ReadableObjMode<{myData: string}>();
typedReadable.push({something: 'else'}); // will throw compilation error as expected
typedReadable.pipe(...) // non overloaded methods typings supported as expected
The only disadvantage of this solution is lack of typings when calling super.parentMethod (but thanks to the interface ReadableObjStream you have all the typings when using instance of ReadableObjStream.
@nin-jin @bioball Thanks for the contributions with the decorator compile-time checking.
Unfortunately it doesn't seem to work with protected members, only with public.
(example of error in my fork of nin-jin's playground