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();
}
}
@aetherealtech The reason I'm not very empathetic toward the Fragile Base Class problem is that it's one of those problems that is almost entirely self-inflicted. To inherit from a class that wasn't intended to be inherited and to override behavior of that class is not an action to be taken likely, and if you've ended up breaking the class in the process, it is entirely your fault. If this is a regular problem for you, then maybe it's your development methodology that needs changing rather than all programming languages.
While it's a good idea to design a language in a way that prevents programmers from shooting themselves in the foot, it's less of a priority when its with a gun they probably shouldn't have been holding in the first place. If this was a ticket about adding goto support, we probably wouldn't even be having this conversation for precisely the same reason.
And for the record, the difference between this and other things that separate us from assembly (like, say, null safety or an automatic garbage collector) is that those things help prevent mistakes that are incredibly easy to make even when you're being careful and trying to follow best practices.
To inherit from a class that wasn't intended to be inherited and to override behavior of that class is not an action to be taken likely, and if you've ended up breaking the class in the process, it is entirely your fault.
Over 60% of all software engineers in the world have 5 years or less of programming experience, and they don't know better.
(source: https://www.developernation.net/developer-reports/dn26/)
"You screwed up and it's your fault," isn't a good reason to not make final classes available. Many of us are writing classes that other (junior) software engineers will use and maintain later, and we'd like to help prevent them from screwing up. It's not their fault that they don't know what they don't know.
@paulshryock No, you're right, it's not their fault. It's yours. It's the fault of their teachers, professors, seniors, peers, and mentors for not teaching them good conventions before ushering them into the professional world. When a junior programmer overrides a class that they shouldn't have overridden and it ends up breaking everything, who is that on, exactly?
This isn't something like which architecture to use or which testing methodology is better. This is up there with "don't use gotos/singletons/global variables without a damn good reason" that every professional developer should know regardless of level of expertise. You are demanding that programming languages implement features that ultimately only serve to make up for the failings of education and professional support systems. What's next? Do we implement a language feature that makes it impossible for junior programmers to waste their time with micro-optimizations and convoluted one-liners?
This isn't merely a case of "you screwed up and it's your fault", because that can be said of just about every language feature that gets misused. This is a case of "you screwed up and it should be immediately obvious how you screwed up without the language needing to tell you that you screwed up".
You wouldn't advocate that a carpenter pad their hammers on the off chance their apprentices might start smashing their tables in half.
And here's another reason why I don't like this feature as just a simple final marker. Because sometimes developers do know what they are doing, and sometimes they do have a good reason to subclass that wasn't intended to be subclassed. final prevents them from being able to do that, forcing them to reimplement the entire system from scratch in order to do what they want. And making final the default behavior is even worse because it puts the burden on the library maintainer to anticipate what should be subclassable which is an exercise in futility. All this feature is doing is catering to the lowest common denominator at the expense of people on the other end of the spectrum.
The only reason to support final as a feature is if we wanted to force programmers to develop with certain paradigms, and that flies in the face of the modern multi-paradigm world. Give your juniors a toolbag and teach them what the tools do, then let them make their own mistakes. Don't give them a hammer and tell them to only concern themselves with the nails.
I agree with a previous poster that what concerns me is not the decision to turn down this feature request but the illogical reasoning being used to justify that decision.
I'm actually surprised that there seems to be (unanimous?) agreement that subclassing/overriding is usually incorrect, and whether it is or even can be correct in a given circumstance is determined by the implementation of the class being overridden (the base class) rather than the proposed override... but that these points are being submitted as justification for not giving class authors the ability to control and forbid overriding their classes.
To help clarify, what I would expect to see as a counterargument against this feature is an argument that forbidding overrides is needlessly restrictive and incorrectly anticipates a lack of possible, valid, unforeseen by the base class author, overrides. If that were the case, final would be giving class authors a power they really shouldn't have. It would either be never correct, or correct in only such a minority of situations to not be significant, to close off overriding, because there's no way for a class author to know if anyone might have a valid use case for an override.
But everyone seems to be in agreement that isn't true. The class author is the one who knows whether a valid override is possible, and is responsible for implementing the base class in a way that allows it. In that case, isn't final the language feature that expresses this opinion on the matter?
For example, Stroustrup argues that you can't ever be sure that no one should want to subclass your class. A subclass can add additional fields that will pass through code that works with the class transparently. It's a purely additive change. It's rather method overrides that can cause trouble, so in C++ you can't close off a class to being extended but you must opt into subclasses being allowed to override methods (using virtual) or access non-public members (using protected).
If you agree with his reasoning, you would reasonably oppose supporting final on classes (I get his point and agree final on methods is much more important, I also don't have an issue with forbidding subclasses entirely though, especially in languages with a proper interface concept).
But I'm not hearing any arguments like that. I'm just hearing arguments about how it's so wrong to freely subclass and override that it would somehow insufficiently signal how wrong it is to allow the language to forbid it. It's an argument I've heard before (like from C developers opposed to smart pointers because developers should be trained to do manual memory management better) that's never made sense to me. It's not a matter of not understanding the problem but standard human forgetfulness and tedium.
Just the other day I refactored a TypeScript design from a base type to an base abstract class with one abstract member and a method that uses that abstract member but shouldn't be overriden itself. The old design was implementing that method in each concrete class, so those became overrides after the refactor and needed to be deleted. It would have been nice for the compiler to throw an error if I overlooked one. It's not an issue of me being naive enough to think the method should be overridden. I know it shouldn't, and I'd like the tooling to help me enforce that and bring my attention to anywhere it's being violated.
If I decide it's correct to subclass a third party class, but then on an update to that dependency the base class design changed and this override no longer works, I'd like to be alerted to that as soon as I upgrade the dependency, and not have a chore to go read and become an expert in the class's private implementation every time I upgrade the dependency. The author can signal this update by adding final which will break my override and force me to fix it.
I also find it surprising the, "just don't use it incorrectly" argument is appearing in the context of TypeScript. This is exactly what TypeScript is for! In JavaScript to call a function correctly you have to go study the implementation of it to know how many and what type of arguments to pass in, and what you're going to get back. And anyone who calls it has to restudy it every time it changes. TypeScript renders this situation (which I consider to be insane, possibly from bias working in statically typed languages) sane by adding a typed signature to a function's interface, the public part that callers need to be familiar with, precisely so they don't have to go study the implementation repeatedly to know how to use it correctly.
You seem resigned to the inevitability that classes are just fragile, that's the way it is and has to be. But that is because there's no way for the author to control overrides. If the language supports that, and class authors are trained to use it appropriately (anything not marked final must be freely overridable without breaking the base class's invariants), then classes won't be fragile anymore! Isn't this better than chastising developers for not treading lightly enough atop unfixably fragile classes?
I don't want to oversell it. TypeScript has a huge ecosystem of classes, some very common and built deeply into foundation APIs like browsers or Node, and sealing off most of them (or most of their methods) with final is a breaking change that each class author would have to opt into, which could render large amounts of dependent code broken (but revealing by doing so that all that code is really brittle and risks accidentally breaking on a dependency update anyways). Alternatively, it at least encourages them to decide that if they're not going to add final, they must design the class to allow overrides. Simply adding the keyword to the language won't suddenly fix the fragility of classes in the TypeScript ecosystem.
But it both enables a way to prevent the problem from getting worse, and at least provides the tools to incrementally patch those holes over time. Without this language feature, TypeScript classes are forever doomed to being fragile. The senior developer who knows his stuff will probably, correctly, deal with this by for all intents and purposes banning subclassing/overriding in his code (at least of third party classes). But this isn't good either, because that closes off opportunities to correctly and safely use those language capabilities.
I don't see how this is an issue of developer training. The unfettered ability to incorrectly override certainly isn't supplying the training the professors dropped the ball on, it's rather letting the untrained developers crash their cars on the highway we all drive on, and forcing the properly trained developers to drive ultra slowly (better than recklessly fast but worse than a sensible speed limit) because they know the highway is unsafe.
Also, wouldn't an untrained developer having the idea to use inheritance to solve a problem, then being blocked from doing so because the class/method he wants to override is final, be an effective way to provide this training? Wouldn't it force the very conversation the untrained developer needs in a real world, non-academic context that makes it meaningful and memorable?
Hand-wringing against final as part of professional software development seems exceedingly silly to me.
Dart 3 last year introduced class modifiers including keywords such as final, base, and sealed (sealed classes can only be extended in the file in which they are declared, which also benefits exhaustiveness checking in pattern matching; note Dart doesn't have type unions so using classes is the only way to do a lot of things... anyway, not to distract from the larger point). Here's how they announced it:
A third Dart 3 language feature is class modifiers. Unlike records & patterns that we expect every Dart developer to use, this is more of a power-user feature. It addresses the needs of Dart developers crafting large API surfaces or building enterprise-class apps.
Class modifiers enable API authors to support only a specific set of capabilities. The defaults remain unchanged though. We want Dart to remain simple and approachable. So, like before, regular classes can be constructed, extended and implemented, as shown in the following examples:
...
- With a
final class, you can close the type hierarchy preventing any subclasses outside of your own library. As a sample benefit, this allows the API owner to add new members without risking breaking changes to the consumers of the API.
Dart previously had fewer distinctions than TypeScript, not distinguishing between an interface, a class, and an abstract class (IIRC). There's no objective grounds to argue against such niceties, even if each language makes different decisions about what to support.
I see now the argument was submitted against final that the class author shouldn't be able to forbid all overrides because he can't anticipate a possible valid one and would be needlessly closing that off by marking things as final.
But I think this is misunderstanding the correct use of final, and also favoring easiness over correctness and especially stability through modification.
An override risks breaking a class's invariants. For an override to not break an invariant the base class's implementation needs to follow rules to ensure it doesn't inappropriately rely on behavior an override could change.
Thus, a class author is always faced with a decision: invest the time to ensure a class's invariants can't be broken by overrides, and allow those overrides, or remove the need to make this investment (which competes with other priorities) by forbidding overrides. The decision isn't just a matter of the class author having a potential valid override in mind, but rather whether it's worthwhile to ensure an override is safe, or decide the risk of broken invariants is small enough to offer the class with "no warranty" so to speak, or at least a warning that overriding a method hasn't been carefully considered/tested and to do it at your own risk.
On the matter of a class author perhaps incorrectly adding final forcing a client to reimplement the class's behavior, that's generally not necessary. There are various design patterns like Decorator or Proxy that work by wrapping a class instance in another class that forwards methods to the wrapped instance, and has an opportunity to intercept and modify them. This is actually more flexible than subclassing because the "base" class can be assigned, and even changed at runtime.
The wrapping class isn't recognized by code written to use the sealed class, so the underlying instance has to be unwrapped and passed into this code, which means that code can't use the modifications. If this is really necessary, some of that code that uses the class might also need to be wrapped with similar patterns. There is a lot of boilerplate to this (although JavaScript is dynamic enough it probably doesn't need to be manually typed out) but you shouldn't have to reimplement anything.
Of course it's possible for class authors to misuse final and render this wrapping technique more pervasive than it should be, but developers can misuse every feature, and also it's important that all that code using the class as is might not have been designed to work with a modified version of the class. What is more important: making it easier to solve a problem correctly (i.e. no wrapping boilerplate), or making it harder to solve it incorrectly (not letting you just pass a modified subclass directly into code not designed with that in mind)?
The worst risk is that passing a subclass with modified methods to that code works accidentally today, and then breaks on an update to that code (not your subclass). This is basically as bad as undefined behavior. The error will occur in a place that might not signal what the problem is, and you can't really protect against the risk except, ironically, by refusing to use a subclass at all.
I will show my hand: my bias is strongly in favor of the latter. I write code that prioritizes making it impossible to write bugs over making it easier to finish a task. I know some developers disagree with this and reply with things like, "just don't write bugs" or "just test your code" (but I am, see this compiler safety is the test!). I can evangelize my perspective here but I think it's more important just to clarify that's the tradeoff, and it's why I favor (as I said at the beginning) everything being final until an explicit decision for it not to be. I'm choosing safety and compile time debugging over speed, under the assumption that overriding is unsafe until explicitly considered and designed to be safe.
maybe it's your development methodology that needs changing rather than all programming languages.
Anyone not living under a rock knows that most other programming languages have already changed. Modern langs are final-by-default, and often have multiple final keywords. Legacy langs have a final keyword. Ancient langs don't.
It's yours. It's the fault of their teachers, professors, seniors, peers, and mentors for not teaching them good conventions before ushering them into the professional world
This sounds like a C++/assembly JavaScript "real programmer", not a TypeScript programmer. People who think final and other type safety features are for wimps can always go back to using JavaScript. They just shouldn't hold back this feature at the expense of the rest of us.
Anyone not living under a rock knows that most other programming languages have already changed. Modern langs are final-by-default, and often have multiple
finalkeywords. Legacy langs have afinalkeyword. Ancient langs don't.
☝ This.
I know a lot of engineers and developers like to make fun of PHP as being behind the times, but even PHP has had final classes since 2004. It's bonkers that in the year of our Beyonce, 2024, TypeScript still doesn't have final classes.
And the reason is... checking my notes... senior engineers are supposed to teach junior engineers about the pitfalls of class extension? Nice. So next time my company brings in new contractors to the team, we'll all drop everything, miss our deadlines, and teach them about programming for a few weeks.
Meanwhile, the rest of us would like to just get work done and use decent language features like final classes. 🤷
Most of requested features needed only for "advanced" or "complex" rare use cases will never see the light of day
There is nothing advanced or complex about final classes or methods. This is basic fundamental object-oriented programming.
Well, that's what the quotes mean! Although, it's certainly more advanced than var.
Either way, that's all you got from the post? 🤦♂️ that's not the point, it is that "most users" won't make use of this and that's the "reasonable" expectation before implementing a feature.
Also, just showing a hack that can achieve the desired compilation error in the meantime. Which I'll be deleting since you're just a bunch of ungrateful ones.
you're just a bunch of ungrateful ones
@miguel-leon, I'm sorry if I made you feel like your comment wasn't welcome. Your opinion is just as valid as mine.
I was disagreeing with part of what you said, and explaining why I disagreed. Disagreeing isn't a bad thing, is it? I like hearing opinions which are different than mine; that's how we all learn.
"most users" won't make use of this
How do you or I know what most users will do? 🤷
I realize OOP isn't trendy on social media right now, and I probably won't find popular YouTubers writing final classes in their videos. But Object-Oriented Programming is a fundamental concept in Computer Science. It's been around since the 1950's, prominently-used since the 1970's and 1980's, and became the dominant programming paradigm in the 1990's. (source)
And many of us out here using OOP on a daily basis to get work done would love for TypeScript to fully embrace OOP instead of ignoring important aspects of it. We'd rather not have to use hacks to achieve very basic functionality.
@paulshryock I wasn't giving an opinion, the only thing mine, was the hack. And you were not disagreeing with me, because I also think there's nothing complex at all.
How do you or I know what most users will do?
Exactly, that's also what quotes meant there. It's part sarcasam and part that's the team general sentiment when some feature doesn't get enough trackion or "convincing" reasons. Not my opinion. Although I understand it's because it's their project, their budget and they decide what to do. (unless someday they make it free for anyone to PR whatever feature they'd like).
The problem is that you didn't understand well that sarcasm or the meaning of my quotation marks. My bad for being confusing.
We'd rather not have to use hacks to achieve very basic functionality.
Again, the hack is for the meantime, in case it was useful to anyone, as this issue is even closed and this feature isn't coming anytime soon. It was useful to me for instance, because I rather have a makeshift final than no final at all.
Stephen Colebourne recently had this talk (albeit for Java) in which he said
So the best practise here [with immutability] clearly is to favour immutability - final classes, final fields.. keep all the mutability you can, ideally, within a source file. So if you've got a source file and you need to do something mutable, keep the mutability within that file, and maybe really knock people on the head in code reviewing by naming the parameters and the variables "mutableSomething". It should be unusual, it shouldn't be the norm. If you can do that, you'll end up with the code that is simpler and better to use in multi-threading.
The entire thing is less than 50 minutes, and well worth a watch, but here's the link with the timestamp to the quoted section.
Going back to the comment about final being an "advanced" or "complex" feature if that was the implication, I'd say we can look at this two ways.
We can go the Java approach where naive implementations of a class don't use final because it wasn't thought about in an open-closed pattern way, but advanced developers will specifically design classes that are open for extension by making API methods public final.
So Java, like Javascript is non-final by default.
If we consider Kotlin though we don't have the final keyword. For references we get val vs var (like const vs let in Javascript), and for methods, they are final by default unless declared open.
Kotlin is a competitor to Typescript, and it just makes sense to use it instead of Typescript for larger codebases, for this reason. final in Typescript would at least upgrade Typescript to give advanced developers such as library authors some options.
If we consider Kotlin though we don't have the final keyword. For references we get val vs var (like const vs let in Javascript), and for methods, they are final by default unless declared
open.
Yes, final by default would be preferable. But if we can't have that (because Microsoft rejects it, or because it's considered too big of a breaking change by the community), then final as a possibility is pretty critical.
@mhegazy ~9 years later, and after a considerable amount of feedback, can you consider reopening the issue? I feel there's enough points in here to justify taking another look.
I'm not sure I understand why final is so hotly debated.
| Include | Exclude | |
|---|---|---|
| Pros | Stronger layer separations Less programmer confusion More use of modular code -> smaller codebases -> faster loads | ?? Maybe keeps language lean |
| Cons | More work and documentation for TS maintainers Possibly slower compilers | Leaves a gap in the language specification that makes it feel less mature than other OOP languages |
Bro, even JavaScript have immutables like const keyword. Why do classes have to be mutable?
On Fri, Dec 5, 2025, 7:21 PM Dave @.***> wrote:
dderiso left a comment (microsoft/TypeScript#8306) https://github.com/microsoft/TypeScript/issues/8306#issuecomment-3618814085
I'm not sure I understand why final is so hotly debated. Include Exclude Pros Stronger layer separations Less programmer confusion More use of modular code -> smaller codebases -> faster loads ?? Maybe keeps language lean Cons More work and documentation for TS maintainers Possibly slower compilers Leaves a gap in the language specification that makes it feel less mature than other OOP languages
— Reply to this email directly, view it on GitHub https://github.com/microsoft/TypeScript/issues/8306#issuecomment-3618814085, or unsubscribe https://github.com/notifications/unsubscribe-auth/AHY5WGQNZ7PANATW5IVCWWD4AIANLAVCNFSM4CB7YM32U5DIOJSWCZC7NNSXTN2JONZXKZKDN5WW2ZLOOQ5TGNRRHA4DCNBQHA2Q . You are receiving this because you commented.Message ID: @.***>
Because Microsoft.
10 years later: nope.