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

@sam-s4s We want the define too :-)

Example of issue..

Initial

class Base {}
class Entity extends Base {
    id() {
        return 'BUG-123' // busisess entity id
    }
}

Base class refactored

class Base {
    id() {
        return '84256635572' // storage object id
    }
}
class Entity extends Base {
    id() {
        return '12' // busisess entity id
    }
}

We got accidental overload here.

Case with define keyword

class Base {
    define id() {
        return '84256635572' // storage object id
    }
}
class Entity extends Base {
    define id() {
        return '12' // busisess entity id
    }
}

Shold be error: Accidental redefine. Use override keyword to override base class method.

Workaround with decorators

nin-jin avatar Nov 10 '20 11:11 nin-jin

@nin-jin isn't define the same as not using override?

lorenzodallavecchia avatar Nov 10 '20 12:11 lorenzodallavecchia

@sam-s4s We want the define too :-)

Oh, I've not seen anyone here mention a keyword define - but from what you describe, I assume you mean like the word virtual in C# ?

(also I found you example a little confusing, as your classes Base and Entity are not related. Did you mean for Entity to extend Base?)

I guess there are 2 scenarios... a) you write your base class, assuming everything without final can be overridden. b) you write your base class assuming everything without virtual cannot be overridden.

sam-s4s avatar Nov 10 '20 20:11 sam-s4s

@sam-s4s Entity extends Base, of course. :-) I have fixed my message. virtual is about something else. @lorenzodallavecchia not using override is define | override for compiler. Using define is only define and compiler can strict check this.

nin-jin avatar Nov 11 '20 13:11 nin-jin

@nin-jin In your model, this means not using the override keyword is still legal, right? For instance:

class Base {
  myMethod () { ... }
}

class Overridden extends Base {
  // this would not fail because this is interpreted as define | override.
  myMethod () { ... }
}

Ideally, the above example produces an error unless you use the override keyword. Albeit, I imagine that there would be a compiler flag to opt-out of override checking, where opting out is the same thing as override | define for all methods

bioball avatar Nov 11 '20 16:11 bioball

@bioball yes, it's required for compatibility with a lot of existed code.

nin-jin avatar Nov 11 '20 17:11 nin-jin

@sam-s4s Entity extends Base, of course. :-) I have fixed my message. virtual is about something else.

I'm still not sure what you mean by define... this is the definition of virtual in C#:

The virtual keyword is used to modify a method, property, indexer, or event declaration and allow for it to be overridden in a derived class.

Maybe you mean the opposite, where, instead of needing to mark the function as virtual in order to override, you can mark the function as define to then mean you have to use the override keyword to override it?

(why define? I have not seen that keyword in another language)

sam-s4s avatar Nov 12 '20 20:11 sam-s4s

I skimmed through this thead in a couple minutes, but I haven't seen anyone propose using override as a way to avoid duplicate specification of parameters and return values. For example:

class Animal {
    move(meters:number):void {
    }
}

class Snake extends Animal {
    override move(meters) {
    }
}

In the above example, move would have the same required return type (void) and meters would also have the same type, but specifying it wouldn't be necessary. The large company I work for is trying to migrate all our javascript to typescript, away from Closure compiler typing. However, while in Closure we can just use @override and all the types will be inferred from the superclass. This is quite useful in reducing the possibility for mismatch and reducing duplication. One could even imagine implementing this such that extension of the method with additional parameters is still possible, even while not specifying types for the parameters that are specified in the superclass. For example:

class Animal {
    move(meters:number):number {
    }
}

class Snake extends Animal {
    override move(meters, time:number) {
    }
}

The motivation for me coming here and writing a comment is that our company is now requiring that we specify all the types even for overridden methods, because typescript doesn't have this functionality (and we're in a long migration). Its quite annoying.

fresheneesz avatar Dec 03 '20 00:12 fresheneesz

FWIW, while it's easier to write, omitting parameter types (and other instances of cross-file type inference) hinders readability, since it requires someone unfamiliar with the code to dig around to find where the superclass is defined in order to know what type meters is (assuming you're reading it outside an IDE, which is quite common for unfamiliar projects where you don't have an IDE set up yet). And code is read much more often than it's written.

shicks avatar Dec 03 '20 01:12 shicks

@shicks You could say that about literally any imported variable or class. Duplicating all the information you might need onto a single file defeats the purpose of abstraction and modularity. Forcing types to be duplicated violates the DRY principle.

fresheneesz avatar Dec 03 '20 01:12 fresheneesz

If I can share my 2 cents.

Since override is somehow contraintuitive for javascript developers (where all start as public and "overridable" for default). Why don't we think about add a final ?

abstract class MyBase {
   myRegularMethod(): {}
   final myFinalMethod(): {}
}


class MyImplementation extends MyBase {
   myRegularMethod(): { 
     /// Everything works here! 👍 
   }

// Compiler error!!!  myFinalMethod is final💀  
   myFinalMethod(): { 
    
   }
}

That would be backwards compatible.

distante avatar Jan 18 '21 10:01 distante

@distante as pointed out here, override and final solve 2 different problems

tmtron avatar Jan 18 '21 10:01 tmtron

@distante as pointed out here, override and final solve 2 different problems

Oh really sorry, I missed it.

If this helps somebody, there is a tslint rule to force a @override comment here.

distante avatar Jan 18 '21 11:01 distante

If I can share my 2 cents.

Since override is somehow contraintuitive for javascript developers (where all start as public and "overridable" for default). Why don't we think about add a final ?

abstract class MyBase {
   myRegularMethod(): {}
   final myFinalMethod(): {}
}


class MyImplementation extends MyBase {
   myRegularMethod(): { 
     /// Everything works here! 👍 
   }

// Compiler error!!!  myFinalMethod is final💀  
   myFinalMethod(): { 
    
   }
}

That would be backwards compatible.

Because with a final you prevent the use of that method in the extended class as with override that is permitted but you need to explicitly mention your intent and the writer of the super/base method will know that whoever overrides it will make a conscious choice to call the super method or not.

As for the familiarity of javascript developer with override, that is not necessarily a valid argument. So is the case with other features that TypeScript has over JavaScript and that is the exact reason why it is used. The functionality can however be an option "explcitOverride" that is turned off by default

aipirvu avatar Jan 18 '21 11:01 aipirvu

What's the latest update? seems like it's still unclear and it's been almost 6 years...

aprilmintacpineda avatar Jan 19 '21 15:01 aprilmintacpineda

What's the latest update? seems like it's still unclear and it's been almost 6 years...

Actually there's a PR: https://github.com/microsoft/TypeScript/pull/39669

Kingwl avatar Jan 19 '21 16:01 Kingwl

seems its also still planned to be included in the next release: https://github.com/microsoft/TypeScript/issues/41601 (at least at the time of writing this)

felixhirt avatar Jan 20 '21 14:01 felixhirt

Thank you @Kingwl, and thank you @pcj for the groundwork in the initial proof-of-concept!

DanielRosenwasser avatar Mar 26 '21 23:03 DanielRosenwasser

I'm not sure where to ask this, but it seems like tsc is compiling and leaving the override keyword in the compiled result. Is this something other folks are seeing? It seems like it needs the signature to match exactly, or it will show up in the output, see here:

https://www.typescriptlang.org/play?ts=4.3.0-beta#code/LAKAxgNghgzjAEBlADgUwheBvUp72QFcAjCASzHgHNUAXAYQAsoAnGmACgEoAueAO0IBbYqhbY8+eCzqEW-eAAYA3JIC+uEPiKkK1OgBE5UWmQD2-bn0EixErVJm05Cles3aS5SmFi0r8ABuZmQAJtgaIJGgkLAIABJmEACeAILG8KgAHrSo-KEIKOiYOCCSZoFiLGGo+gzMbKicXPZS0rLy8ACMbg7RDhVVNXVGLCbmlrwCwqLipW1OLvAAzL34-fiDLNWhtb4w-lPBYa3w-WpAA

seiyria avatar Apr 05 '21 15:04 seiyria

Also .d.ts file is missing override. Is it by design? aka for back compat with old ts compilers

abdulkareemnalband avatar Apr 05 '21 15:04 abdulkareemnalband