Support final classes (non-subclassable)
I was thinking it could be useful to have a way to specify that a class should not be subclassed, so that the compiler would warn the user on compilation if it sees another class extending the original one.
On Java a class marked with final cannot be extended, so with the same keyword on TypeScript it would look like this:
final class foo {
constructor() {
}
}
class bar extends foo { // Error: foo is final and cannot be extended
constructor() {
super();
}
}
Ah if I recall I was reading a lots about the ES4 (I am unsure I was still a kid when the draft was in productions lol) and surprisely it's look really similar to Typescript.
and it's say in the draft specifications here : https://www.ecma-international.org/activities/Languages/Language%20overview.pdf
A class that does not explicitly extend any other class is said to extend the class Object. As a
consequence, all the classes that exist form an inheritance hierarchy that is a tree, the root of which is
Object.
A class designated as final cannot be extended, and final methods cannot be overridden:
class C {
final function f(n) { return n*2 }
}
final class D extends C {
function g() { return 37 }
}
so Technically the final keyword was planned into the Ecmascript 4th edition. Do we will see it in the futur integrations of JS I doubt about it but they indeed integrated class so this might be possible but who know?
I have one use case that I just barely ran into that drove me to find this issue. It revolves around the use of this as a return type:
abstract class TileEntity {
//constructor, other methods...
abstract cloneAt(x: number, y: number): this;
}
My intention in writing this was to ensure that TileEntities are immutable (and therefore safe to pass around) but that any given TileEntity could be cloned with a few changed properties (in this case x and y) without having to know anything about the shape of the subclass. That is what I want to write, but attempting to write an implementation (correctly) causes this to break.
class TurretTileEntity extends TileEntity {
//constructor, other methods...
cloneAt(x: number, y: number): this {
return new TurretTileEntity(x, y, /* ... other properties */);
}
}
The problem is that without being able to declare that there will never be a subclass of TurretTileEntity, the this return type cannot be narrowed down to just the type TurretTileEntity.
The impact of this shortcoming in Typescript is minimal, considering you can cast the return value to <any>. This is, objectively, an antipattern, and a useful indication that the type system could be more expressive. Final/sealed classes should be supported.
Out of interest, when the TypeScript team sat around a table and discussed abstract classes, did anyone raise their hand and say "but what about final"?
Yes. Every time we add a keyword, "but then we'll have to add this other keyword too!" is a strong point against adding it, because we want to grow the language as carefully as possible. final on class declarations is in this camp as well - if we have final classes, then we'll "need" final methods or properties as well. Anything that looks like scope creep is regarded with extreme suspicion.
I think that final classes and methods are very important. I hope you will implement it.
Note that this issue is about final/sealed classes. There's been off-topic discussion of final/sealed methods which are a completely different concept.
mhegazy closed https://github.com/Microsoft/TypeScript/issues/9264 in favor of this issue. Is there a separate issue that is not closed as a dupe to track final/sealed methods?
@crcla From reading some of @RyanCavanaugh's comments above, I believe the rationale for closing the other issue is because supporting final/sealed classes encompasses supporting final/sealed methods. The two are quite closely related topics.
I can not believe the propose for final is labeled as Won't fix.
Change the label back to In Discussion and implement it, please!
In my case, I want to write an abstract base class for the plugins and I want to make sure that the plugin class can not overwrite my base class methods by mistake. None of the private constructor, Object.seal can do this job.
To those who see this as a crucial, live-or-die feature: it's really not. If your API consists of exposing a class implementation that needs to be extended by the consumer, there are better ways to do this. Don't follow React's bad example. Just use functions and simple objects, and leave this OO nonsense where it belongs: in the past.
Now bring on the downvotes 😀
Could someone explain me how this discussion does not distinct between final classes and final methods? Of course preventing some methods from overriding adds enormous value. I want to provide the possibility for a plugin developer to add functionality by subclassing some of my frameworks classes and implementing abstract functions - but at the same time make sure she does not (why ever!) override the methods that call these abstract functions (and make sure the error handling/loggin/checking takes place.
@pelotom If you don't want to use OOP constructs and patterns, just don't, no one's telling you to do otherwise, however the same should apply in the opposite direction: if someone wants to use OOP constructs, just let them. By forcing others to adopt a specific (non-OOP) pattern, you're adopting the same behaviour as the one you denounce OOP for. At least be consistent :)
Adding a final keyword to TypeScript is not a breaking change and won't influence any of your existing projects in any way, however it will be a vital feature for people such as @thorek, myself, and many others.
if someone wants to use OOP constructs, just let them.
We’re not debating whether people should use OOP constructs, we’re debating whether currently non-existent OOP constructs should be added to the language. Doing so takes developer time that could be spent on other features, and makes the language more complex, which slows the rate of future features (because for every new feature it must be considered how it will interact with every old feature). So it certainly does affect me, because I’d rather spend TypeScript’s development and complexity budget on more useful things!
fwiw, we're probably going to encourage our customers (google) to use @final in comments so it propagates to closure compiler :\
Adding final on classes and methods is useful when an R&D team builds TS libraries that other teams can use. These keywords are (an important) part of service exposure stability of such tools. The keyword is more important for large teams and less important for small projects, imho.
@dimiVergos This is exactly my case, and I assume the same for many others. I can imagine I may seem biased due to my position, but it seems the only (albeit highly) justifiable use of this keyword according to my experience.
I'm open to corrections on this one!
I care more about supporting final methods (to avoid subclasses accidentally overriding them) than I do final classes. Is the the right ticket to vote for that? Ticket https://github.com/Microsoft/TypeScript/issues/9264 seems to imply so.
So how do I vote for "final methods"? Or did I just vote for it by this comment? Also how do we add "methods" to the title? Can I just edit it? The current title is misleadingly limited solely to classes but the discussion includes methods too.
Like many others I would like to see final methods in TypeScript. I've used the following approach as a partial workaround that is not immune to failure but at least helps a little:
class parent {
public get finalMethod(): () => void {
return () => {
// final logic
};
}
}
class child extends parent {
// ERROR "Class 'parent' defines instance member accessor 'finalMethod', but extended class 'child' defines it as instance member function"
public finalMethod(): void { }
}
Here's another real world use case for final methods. Consider the following extension of a React.Component to make it easier to implement a simple Context.
interface FooStore{
foo: string;
}
const {Provider, Consumer} = React.createContext<FooStore>({
foo: 'bar';
});
abstract class FooConsumerComponent<P, S> extends React.Component<P, S> {
// implement this instead of render
public abstract renderWithStore(store: FooStore): JSX.Element;
public final render() {
return (
<Consumer>
{
(store) => {
return this.renderWithStore(store);
}
}
</Consumer>
);
}
}
Without final on the render() method, nothing stops one from incorrectly overriding the method, thus breaking everything.
Hi, like many others I would like "final" or "sealed" keyword at least for methods. I totally agree that this keyword is a really added value as it allow developper to prevent their librairies customer to extend crucial code blocks (like in plugin for example).
The only workaround I found is to use method decorator like :
function sealed(target, key,descriptor){
descriptor.writable = false; // Prevent method to be overriden
}
then in your "base" class, use decorator to prevent method override, example :
class MyBaseClass {
@sealed
public MySealedMethod(){}
public OtherMethod(){}
...
}
This way 'MySealedMethod' couldn't (easily) be overriden in sub class. Exemple:
class AnotherClass extends MyBaseClass {
public MySealedMethod(){} ====>> ERROR at RUNTIME (not at compile time)
}
actually, the only downside of this workaround is that the "sealed" is only visible at runtime (error in javascript console) but NOT at compile time (as the method properties are set via function I guess)
@RyanCavanaugh
Yes. Every time we add a keyword, "but then we'll have to add this other keyword too!" is a strong point against adding it, because we want to grow the language as carefully as possible.
It seems to me that you're starting this argument with your mind set up against the feature. A popular feature should not be a point against considering such feature. It should be a point towards asking yourself why it's popular, and then carefully consider it.
I'm sure you've discussed it and arguments have been flung around towards considering it or against it. Is the argument against it just that it's feature creep, or is there anything more specific? Do you consider it a fringe feature? If so, could we do something to change your mind?
Let me just leave these questions here for all of us to ponder.
Is there a way to seal a class by design using present constructs? If the feature was added, would it allow us to do anything new? (As in, something present constructs don't permit) If the feature did allow us to do something new, is it something valuable? Would adding sealed classes increase language complexity too much? Would adding sealed classes increase compiler complexity too much?
For the purpose of discussing these, I'm not including sealed methods in the discussion and I'm also not including run-time checks in the implementation. We all understand we can't enforce this on Javascript.
FYI: I'd be awesome if the counter to this feature was a bit more than just blanket statements against feature-creep.
@asimonf I think everything you've said was already addressed by this comment (you will need to expand the "show more" section to see it) and the one following it.
What would change our mind here? People showing up with examples of code that didn't work the way it should have because the sealed keyword was missing.
The scenario here that the keyword attempts to address is one where someone mistakenly inherits from a class. How do you mistakenly inherit from a class? It's not an easy mistake to make. JavaScript classes are inherently fragile enough that any subclass must understand its base class's behavioral requirements, which does mean writing some form of documentation, and the first line of that documentation can simply be "Do not subclass this class". Or there can be a runtime check. Or the class constructor can be hidden behind a factory method. Or any other number of options.
Why must TypeScript have this keyword when the situation is already one in which you should have had encountered at least two separate roadblocks telling you not to be there to begin with?
I've been programming for approximately forever years now and I have not once tried to subclass something only to find out it was sealed and I shouldn't have tried. It's not because I'm a super genius! It's just an extremely uncommon mistake to make, and in JavaScript these situations are already ones where you need to be asking questions of the base class in the first place. So what problem is being solved?