Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cannot use override keyword to override methods of Object without explicitly extending Object #45704

Open
kmxz opened this issue Sep 3, 2021 · 1 comment
Labels
Awaiting More Feedback This means we'd like to hear from more people who would be helped by this feature Suggestion An idea for TypeScript

Comments

@kmxz
Copy link

kmxz commented Sep 3, 2021

Bug Report

πŸ”Ž Search Terms

override, TS4112

πŸ•— Version & Regression Information

It happens in 4.4.2 and has been there since the introduction of override keyword (#39669).

⏯ Playground Link

https://www.typescriptlang.org/play?#code/MYGwhgzhAECC0G8BQ1oHsBuBTATjglgCZbQAuaAyqQQHYDmAFAJSKo5akCuON0A5ADM0aPgG5oAXyQSgA

πŸ’» Code

class A {
  override toString() { return 'foo'; }
}

πŸ™ Actual behavior

TS4112: This member cannot have an 'override' modifier because its containing class 'A' does not extend another class.

πŸ™‚ Expected behavior

It should be allowed, since the method overrides Object.prototype.toString.

Per ECMAScript spec Β§15.7.12.7, a class without an explicit extends clause would be implicitly inheriting from Object. Therefore, such classes should be allowed to explicitly override methods declared in Object.

@andrewbranch andrewbranch added Awaiting More Feedback This means we'd like to hear from more people who would be helped by this feature Suggestion An idea for TypeScript labels Sep 3, 2021
@kmxz
Copy link
Author

kmxz commented Oct 18, 2021

FYI, I have a fix for this at kmxz@08ef62d. I haven't created a pull request as this issue is not yet labelled "help wanted", but I'm happy to create one at any time.


I do realize that there's another issue with overriding a method declared in Object:

// Error "TS2416: Property 'toString' in type 'A' is not assignable to the same property in base type 'Object'. Type '() => number' is not assignable to type '() => string'".
class A extends Object {
  override toString() { return 0; }
}

// No errors!
class B {
  override toString() { return 0; }
}

It makes sense to issue an error in the second case, since TypeScript already treats all classes as subclasses of Object when resolving property accesses. I'm just a bit concerned that it could be a breaking change for some users.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Awaiting More Feedback This means we'd like to hear from more people who would be helped by this feature Suggestion An idea for TypeScript
Projects
None yet
Development

No branches or pull requests

2 participants