TypeScript icon indicating copy to clipboard operation
TypeScript copied to clipboard

Support override keyword on class methods

Open rwyborn opened this issue 11 years ago • 223 comments

(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:

  1. type override
  2. An auto complete drop down appears of all super methods for the class
  3. A method is selected in the drop down
  4. The signature for the method is emitted into the class declaration after the override keyword.

rwyborn avatar Feb 10 '15 11:02 rwyborn

@JabX I would personally want a warning if a base class added an implementation of an abstract method.

However, I am not 100% sold on the idea of an implements keyword in the first place. The compiler will already warn you if you didn't implement something. The only place that it is really helpful is for optional methods.

And anyway, it has nothing to do with why I am in this thread. I was just looking if there was a way to specify a function as an override of a parent class.

eggers avatar May 07 '16 18:05 eggers

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?

I think not writing it should be a warning.

olmobrutall avatar May 07 '16 20:05 olmobrutall

The only place that it is really helpful is for optional methods.

Yeah, that's kind of the whole point here.

JabX avatar May 08 '16 18:05 JabX

Without this it's very common error to typo method that you would like to override but in fact you are crating new method. Introduction of such keyword is only way to point out intention of overriding function.

That could be warning or whatever but currently it's very painful.

pankleks avatar May 18 '16 13:05 pankleks

I'm adding an override annotation to the UML class view in alm.tools :rose:

image

refs https://github.com/alm-tools/alm/issues/84

basarat avatar May 20 '16 02:05 basarat

I've also added a gutter indicator for class members that override a base class member in alm.

overrides

refs https://github.com/alm-tools/alm/issues/111

basarat avatar May 26 '16 21:05 basarat

Accepting PRs for a scoped solution we think achieves the most value with the least complexity:

  • New keyword override is valid on class method and property declarations (including get/set)
    • All signatures (including implementation) must have override if one does
    • Both get and set must be marked override if either is
  • It is an error to have override if there's no base class property/method with this name
  • New commandline switch --noImplicitOverride (feel free bikeshed the name here) makes override mandatory for things that are overrides
    • This switch has no effect in ambient contexts (i.e. declare class or .d.ts files)

Out of scope at this time:

  • Inheriting signatures
  • Contextual typing of parameters or initializers (tried this earlier and it was a disaster)
  • Corresponding keyword to indicate "I am implementing an interface member with this declaration"

RyanCavanaugh avatar Jun 09 '16 01:06 RyanCavanaugh

@RyanCavanaugh I'm currently trying to implement this (just started, and I'd welcome any help on this, especially for testing), but I'm not sure I understand what's behind

All signatures (including implementation) must have override if one does

Since you can't have multiple signatures of a method in a class, are you talking about the inheritance context? Do you mean that (without the flag that enforces the use of override, otherwise it's obviously an error)

class A {
    method() {}
}

class B extends A {
    override method() {}
}

class C extends B {
    method() {} 
}

should output an error in class C because I didn't write override before method?

If that the case, I'm not sure why we'd want to enforce that. And should it also work the other way around? Output an error in class B if I specified the override in C and not in B?

JabX avatar Jun 18 '16 15:06 JabX

Yes, I think it applies to the inheritance tree signatures. And I don't think it will work the other way around, it should start enforcing the override rule once it's used at a level in the hierarchy. In some cases the decision to apply override may be made on a class derived from a class not owned by the developer. So, once it's used it should apply to all derived classes only.

joewood avatar Jun 18 '16 16:06 joewood

I have another question about

Both get and set must be marked override if either is

What happens there if my parent class only defines a getter and I want to define in my derived class the setter? If I follow this rule, that means that my setter would have to be defined as an override, but there is no setter in the parent class, and it should be an error to override something that doesn't exist. Well, in practice (in my current naive implementation), there is no contradiction since the getter and the setter are for the same property. I could even write something like:

class A {
    get value() { return 1; }
}

class B extends 1 {
   override set value(v: number) {}
}

Which looks plain wrong to me.

JabX avatar Jun 18 '16 22:06 JabX

Since you can't have multiple signatures of a method in a class

You can have multiple overload signatures for the same method:

class Base { bar(): { } }

class Foo extends Base {
  // Must write 'override' on each signature
  override bar(s: string): void;
  override bar(s?: number): void;
  override bar(s: string|number) { }
}

I think your intuition about the other cases is correct.

Regarding getters and setters, I think override just applies to the property slot. Writing an overriding setter without a corresponding getter is clearly extremely suspicious, but it's no more or less suspicious in the presence of override. Since we don't always know how the base class was implemented, I think the rule is simply that an override getter or setter must have some corresponding base class property, and that if you say override get {, any set declaration must also have override (and vice versa)

RyanCavanaugh avatar Jun 20 '16 18:06 RyanCavanaugh

Oh ok I didn't know we could write method signatures in classes like that, that's pretty neat.

JabX avatar Jun 20 '16 19:06 JabX

I think virtual would make sense too. All keywords: virtual, override, final actually would make much difference especially when refactoring classes. I'm using heavily inheritance, it's so easy now to override method "by mistake". virtual would also improve intellisense, as you could propose only abstract/virtual methods after override keyword.

Please, please put priority on these. Thanks!

pankleks avatar Aug 12 '16 22:08 pankleks

I agree with @pankleks - I'm using inheritance a lot, and it just feels wrong to override a function without specifying anything directly.

"virtual", "override" and "final" would be perfect.

This is an important issue for me.

sam-s4s avatar Sep 08 '16 01:09 sam-s4s

@RyanCavanaugh

Contextual typing of parameters or initializers (tried this earlier and it was a disaster)

Can you elaborate on this? I actually found this issue while trying to find out why TS does not infer the type of my parameters on method overrides, which came as surprise to me. I don't see when a non-identical parameter list would be correct when overriding, or a return type which is not compatible.

@pankleks

I think virtual would make sense too.

By its nature everything is "virtual" in JS. Support for final would suffice IMHO: if you have a method (or property) which must not be overridden you could mark it as such to trigger a compiler error when this was violated. No need for virtual then, right? But this is tracked in issue #1534.

avonwyss avatar Sep 09 '16 15:09 avonwyss

@avonwyss there are sort of two issues here.

When we tried contextually typing property initializers, we ran into some problems described at https://github.com/Microsoft/TypeScript/pull/6118#issuecomment-216595207 . We think we have a new more successful approach at #10570

Method declarations are a different ball of wax and there we have some other things to figure out, like what should happen here:

declare class Base {
  method(x: string): string[];
  method(x: number, count: number): number[];
}
class Derived extends Base {
  method(x) { // x: ???
    return x;
  }
}

We may just decide that only single-signature methods get parameter types from the base. But this isn't going to make everyone happy and doesn't really solve the frequent problem of "I want my derived class to method have the same signatures but just provide a different implementation".

RyanCavanaugh avatar Sep 09 '16 16:09 RyanCavanaugh

Well, x's type would be string | number in that case, but I understand that it might be pretty hard to find out consistently.

JabX avatar Sep 09 '16 16:09 JabX

But you probably wouldn't want the externally-seen type of x to be string | number - assuming Derived has the same semantics as Base, it wouldn't be legal to invoke with (3) or ('foo', 3)

RyanCavanaugh avatar Sep 09 '16 16:09 RyanCavanaugh

Hum yeah, I missed that.

I see you suggested to restrict it to single-signature methods, but I believe it could be "easily" expanded to "matching-signature" methods, like in your exemple:

declare class Base {
  method(x: string): string[];
  method(x: number, count: number): number[];
}
class Derived extends Base {
  method(x, count) { // x: number, count: number
    return [];
  }
}

because there is only on signature on the base class that matches.

That would be way better than what we have (nothing), and I don't think it would be that hard to do? (still way out of scope for this issue and probably more work)

JabX avatar Sep 09 '16 18:09 JabX

@RyanCavanaugh Thanks for the reply. As noted my hope for override is that it would sort the parameter (and return type) issue out. But I don't see your example as problematic, since overloads always have to have one single "private" implementation which is compatible with all overloads (which is why the suggestion from @JabX would not work conceptually). So, we'd have something like this:

declare class Base {
  method(x: string): string[];
  method(x: number, count: number): number[];
  // implies: method(x: string|number, count?: number): string[]|number[]
  // or fancier: method<T extends string|number>(x: T, count?: number): T[]
}
class Derived extends Base {
  override method(x, count?) { // may only be called like the method on Base
    return [x];
  }
}

This logic already exists and the override would obviously only be available for the "private" implementation method, not the distinct overrides (just as you cannot explicitly implement a single overload anyways). So I do not see a problem here - or did I miss something?

Methods designed to be overridden usually don't have overloads anyways, so even taking the simple way out and not infer the parameter and return types if overloads exist would be perfectly fine and useful. So even if the behavior was as-is when overriding overloaded methods, you'd get an error when running in --no-implicit-any mode and you'd have to specify compatible types, that would seem like a perfectly fine approach.

avonwyss avatar Sep 09 '16 22:09 avonwyss