TypeScript icon indicating copy to clipboard operation
TypeScript copied to clipboard

Support final classes (non-subclassable)

Open Zorgatone opened this issue 10 years ago • 184 comments

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();
    }
}

Zorgatone avatar Apr 26 '16 13:04 Zorgatone

Java and/or C# uses the final class to optimize your class at runtime, knowing that it is not going to be specialized. this i would argue is the main value for final support. In TypeScript there is nothing we can offer to make your code run any better than it did without final. Consider using comments to inform your users of the correct use of the class, and/or not exposing the classes you intend to be final, and expose their interfaces instead.

What does typescript exactly do in runtime for optimizing??????

All about preventing bugs.

mahdi-farnia avatar Sep 09 '22 17:09 mahdi-farnia

Sadly, over a number of years, the powers that be constantly "misinterpret" a request that is primary related to writing safe and reliable code as something to do with performance. It is quite bizarre.

I think the powers that be got offended early on in the process and now routinely reject anything with the word final in it (e.g. final methods, final classes) as an affront to their dignity.

I can't really imagine any other explanation for the refusal to consider final other than a psychological explanation. It's hard to believe that the highly skilled and intelligent maintainers would actually misinterpret the request over and over and over again.

After all the primary motivation with typescript has nothing to do with performance optimization but rather writing safe and reliable code.

This post is mainly for newbies to set their expectations. I expect no change whatsoever by the maintainers because they are clearly not assessing this on technical merit

Regards Charlie

On Fri, Sep 9, 2022, 1:41 PM SoR @.***> wrote:

Java and/or C# uses the final class to optimize your class at runtime, knowing that it is not going to be specialized. this i would argue is the main value for final support. In TypeScript there is nothing we can offer to make your code run any better than it did without final. Consider using comments to inform your users of the correct use of the class, and/or not exposing the classes you intend to be final, and expose their interfaces instead.

What does typescript exactly do in runtime for optimizing??????

All about preventing bugs.

— Reply to this email directly, view it on GitHub https://github.com/microsoft/TypeScript/issues/8306#issuecomment-1242276761, or unsubscribe https://github.com/notifications/unsubscribe-auth/AAC2EG662YSLPPYUGUWW4A3V5NZGLANCNFSM4CB7YM3Q . You are receiving this because you were mentioned.Message ID: @.***>

cbutterfield avatar Sep 09 '22 18:09 cbutterfield

Instead of riding this dead horse switch over to the well written retry of this whole issue in #50532, give it your whole support at least with thumbs-up reactions and hope this issue is not blindly closed for the wrong reasons again.

kayahr avatar Sep 10 '22 07:09 kayahr

@mahdi-farnia

What does typescript exactly do in runtime for optimizing??????

Initializing members of classes consistently reduces the number of “shapes”, preventing some deoptimization/bailout scenarios. While this is not the primary goal of TypeScript, it does make sense for TypeScript to avoid features which can not be translated into efficient JavaScript equivalents. For example, I would not expect TypeScript to add a concise syntax for an operator which implements a deep equality check that would require full object traversal. That belongs in a library and adding an operator would make the operation appear lightweight to the developer while being heavyweight.

@cbutterfield

Sadly, over a number of years, the powers that be constantly "misinterpret" a request that is primary related to writing safe and reliable code as something to do with performance. It is quite bizarre.

I think the powers that be got offended early on in the process and now routinely reject anything with the word final in it (e.g. final methods, final classes) as an affront to their dignity.

I wouldn’t say this so strongly, but I do agree. TypeScript lead the way with JavaScript language innovation by introducing an implementation of async/await whose syntax was adopted into ECMAScript (even if nuances in behavior are not identical). It even started out with providing class before JavaScript had it. But TypeScript decided that they want to avoid creating features which could force them to deviate from future developments in ECMAScript. They have gone so far with this, that they are no longer willing to innovate or deviate from pure JavaScript behavior even for things which exist entirely in TypeScript’s realm such as nominal or final classes.

It’s understandable that they don’t want to risk making new syntax which conflicts with future changes to ECMAScript. But it comes at the cost of preventing people from expressing certain constraints which would be very beneficial in a static type checker. It is a balance, so a line needs to be drawn somewhere, but it seems to be drawn in a different place than it was when TypeScript was first created, unfortunately.

So… are there any good TypeScript forks? Or is the ecosystem forcing us to stay? Hrm…

binki avatar Sep 10 '22 17:09 binki

Does this help? (At the method or attribute level) TS playground link

declare const _: unique symbol;
type NoOverride = { [_]: typeof _; }

class A {
  readonly baz: string & NoOverride = '' as any;

  // Note - `ReturnType & NoOverride`
  foo(): { a: string } & NoOverride {
    return { a: '' } as any;
  }

  // if this function return nothing, use `NoOverride` only
  bar(): NoOverride {
    console.log(0);

    return null!;
  }
}

class B extends A {
  // @ts-expect-error - Type 'string' is not assignable to type 'NoOverride'.
  baz = '';

  // @ts-expect-error - Property '[_]' is missing in type '{ a: string; }' but required in type 'NoOverride'.
  foo() {
    return { a: '' };
  }

  // @ts-expect-error - Type 'void' is not assignable to type 'NoOverride'.
  bar() {
  }
}

Max10240 avatar Jul 15 '23 07:07 Max10240

@Max10240 doesn't that break external module doing new A().baz = 'asdf';?

binki avatar Jul 15 '23 13:07 binki

@Max10240 doesn't that break external module doing new A().baz = 'asdf';?

Yes. The above answers only apply to the method or attribute level. If you want to make a property to be final , I think it must first be "readonly". I updated the comment to explicitly add the "readonly" modifier!

Max10240 avatar Jul 16 '23 12:07 Max10240

TypeScript lead the way with JavaScript language innovation by introducing an implementation of async/await whose syntax was adopted into ECMAScript (even if nuances in behavior are not identical).

The ES proposal predated TypeScript implementation by over a year and a half.

It even started out with providing class before JavaScript had it.

Classes were included in ES4/Harmony, years before TS existed.


Better examples would be decorators or private members.

Especially private members; TS added them as a type-level feature, but then JS added private members as a language/runtime feature.

It's possible (but unlikely) that JS would do something similar with final classes.

All that said, TS supporting final classes + nominal tying would be very useful.

pauldraper avatar Jul 25 '23 17:07 pauldraper

Sometimes TypeScript design decisions surprise me. How can you both have override but not final? Every reason you have for override can be adapted for final/sealed.

Kinda the same vibes as "not generating anything at runtime" but also having had both the decorators and int-backed enums generate extra code.

Voltra avatar Oct 22 '23 15:10 Voltra

This result is laughable.

EduApps-CDG avatar Nov 02 '23 23:11 EduApps-CDG

I ran into an issue stemming from the lack of sealed that I think introduces a use-case that hasn't yet been covered in this thread. (If it has, I apologize, but it's a very long thread.)

Some languages are coming out with the final/sealed feature but with a twist: the class can be inherited but only from the same file/module that the base class was defined. This extends the idea of an unmodifiable class and adds the idea of a closed enumeration of subclasses, which I think extends to TypeScript nicely as it allows subclasses to be defined in a way that mimics a type union.

Here's an incredibly simplified version of what I was trying to do:

//////////////////
// model.ts

export abstract class Base {
  static factory(): Base {
    // Some logic to return either a Foo or a Bar
  }

  abstract isFoo(): this is Foo;
  abstract isBar(): this is Bar;
}

export class Foo extends Base {
  constructor(public a: string) { super(); }

  override isFoo(): this is Foo { return true; }
  override isBar(): this is Bar { return false; }
}

export class Bar extends Base {
  constructor(public b: number) { super(); }

  override isFoo(): this is Foo { return false; }
  override isBar(): this is Bar { return true; }
}

//////////////////
// index.ts

const val = Base.factory();

if (val.isFoo()) {
  console.log(val.a); // Can access `a` because `val` is now Foo
}

What I'd like to do is be able to tell the compiler that if val isn't a Foo, it must be a Bar. This is something you can do with a type union, but not with subclasses.

if (val.isFoo()) {
  console.log(val.a); // Can access `a` because `val` is now Foo
} else {
  console.log(val.b); // Error: even though the only other subtype of `Base` that I defined was `Bar`, the compiler can't guarantee some other subtype of `Base` doesn't exist
}

If Base was marked as sealed, however, the compiler would be able to know that Foo and Bar are the only subtypes of Base that can exist and inform the type system accordingly:

//////////////////
// model.ts

export sealed abstract class Base {
  ...
}

export class Foo extends Base {
  ...
}

export class Bar extends Base {
  ...
}

...

//////////////////
// model2.ts

export class Baz extends Base { // Error: Baz cannot extend Base as Base is sealed.
 ...
}

//////////////////
// index.ts

const val = Base.factory();

if (val.isFoo()) {
  console.log(val.a); // Can access `a` because `val` is now Foo
} else {
  console.log(val.b); // Succeeds because the compiler knows that if `val` isn't `Foo`, it must be `Bar`
}

Is there a way to accomplish this with just using a type union? Sure.

//////////////////
// model-utility.ts

export type BaseType = Foo | Bar;

export function isFoo(obj: BaseType): obj is Foo {
  return obj instanceof Foo
}

export function isBar(obj: BaseType): object is Bar {
  return obj instanceof Bar;
}

//////////////////
// index.ts

const val = Base.factory() as BaseType;

if (isFoo(val)) {
  console.log(val.a);
} else {
  console.log(val.b);
}

But that approach has several issues for me:

  1. It's idiomatic of an FP-oriented coding style, which is a stark contrast to both my personal coding style and the general coding style of my team at work. (It is what it is.)
  2. It requires additional boilerplate to be written especially if the base types I'm working with come from a library I don't control.
  3. The isFoo and isBar utility functions are separated from the Base/Foo/Bar family of classes which hurts API discoverability.
  4. It's yet another thing I have to import which unnecessarily bloats the import section.

Interestingly, I can combine the two approaches:

//////////////////
// model.ts

export type BaseType = Foo | Bar;

export abstract class Base {
  static factory(): BaseType { // Return type is the type union instead of the abstract class
     // Some logic to return either a Foo or a Bar
  }

  abstract isFoo(): this is Foo;
  abstract isBar(): this is Bar;
}

export class Foo extends Base {
  constructor(public a: string) { super(); }

  override isFoo(): this is Foo { return true; }
  override isBar(): this is Bar { return false; }
}

export class Bar extends Base {
  constructor(public b: number) { super(); }

  override isFoo(): this is Foo { return false; }
  override isBar(): this is Bar { return true; }
}

//////////////////
// index.ts

const val = Base.factory(); // `val` is now of type `BaseType` (i.e. `Foo | Bar`) instead of `Base`

if (val.isFoo()) {
  console.log(val.a);
} else {
  console.log(val.b);
}

Syntactically, this method works, but it has its own issues:

  1. This change affects the entire API as everything that returns Base now has to return BaseType instead. Otherwise, the "solution" won't work.
  2. Conceptually, it just feels wrong that the type of val is now Foo | Bar instead of Base. If I'm using OOP, I would prefer to stay in the realm of OOP.

Abion47 avatar Feb 28 '24 20:02 Abion47

final in the cases of C++ or Java is used for compile-time optimization sure, but it's also used to statically enforce a "contract" for library consumers: you cannot override (or extend for classes' case).

Voltra avatar Feb 28 '24 22:02 Voltra

but it's also used to statically enforce a "contract" @Voltra we learn that in Software Engineering class.

I have a extensible database design (I make plug-ins for my own project) the system plug-ins shall not be extended, so they would be final.

EduApps-CDG avatar Feb 29 '24 15:02 EduApps-CDG

It's bonkers that TypeScript still doesn't have final classes and methods.

I would use final in every project, if it was available.

paulshryock avatar Apr 27 '24 19:04 paulshryock

Every so often I think of this issue, and #33446 (final methods), and the 2016 and 2019 responses from the TypeScript team, and it brings me down, not so much for the rejection of the feature as for being inaccurate or illogical in the reasons given. I wrote a wordy comment in 2021, but I just want to push back more clearly before I give it a rest for another few years.

(1)

If you are reading this, you probably know that the primary purpose of final in Java is not as a performance hint, but for contract enforcement (as taught in intro software engineering, etc). What you may not know (or may misremember) is, it's not a secondary purpose of final, either! Using final to try to speed up methods or classes has been discouraged, and not worked, since the Java HotSpot compiler came out in 1999. Here is a column from October 2002 debunking the myth that one should consider using final for performance reasons (referenced by a 2003 column titled Urban performance legends):

Like many myths about Java performance, the erroneous belief that declaring classes or methods as final results in better performance is widely held but rarely examined. The argument goes that declaring a method or class as final means that the compiler can inline method calls more aggressively, because it knows that at run time this is definitely the version of the method that's going to be called. But this is simply not true. Just because class X is compiled against final class Y doesn't mean that the same version of class Y will be loaded at run time. So the compiler cannot inline such cross-class method calls safely, final or not. Only if a method is private can the compiler inline it freely, and in that case, the final keyword would be redundant.

On the other hand, the run-time environment and JIT compiler have more information about what classes are actually loaded, and can make much better optimization decisions than the compiler can. If the run-time environment knows that no classes are loaded that extend Y, then it can safely inline calls to methods of Y, regardless of whether Y is final (as long as it can invalidate such JIT-compiled code if a subclass of Y is later loaded). So the reality is that while final might be a useful hint to a dumb run-time optimizer that doesn't perform any global dependency analysis, its use doesn't actually enable very many compile-time optimizations, and is not needed by a smart JIT to perform run-time optimizations.

In summary, final: Not a performance thing, at all.

Not a way to "request a low-level runtime behavior" that happens to "imply a type meaning," as Ryan argued.

(Note that final fields are a different story; the point here is about final classes and methods.)

(2)

When asked if, while considering the pros and cons of final methods and final classes, we could discuss them as separate features, Ryan replied:

I don't see any lack of duality between final classes and final methods; the latter is simply a more fine-grained control of the former and the motivations are largely the same.

However, they are separate features, not essentially the same, because:

  • They do different things.
  • If I can't have one, for some technical or moral reason, I still want the other.
  • It's a lot easier to make sure people don't subclass a class than to make sure they don't override a method, such as by accident or after a refactoring, just because it's a harder mistake to make in the first place.
  • Enforcement-wise, it's a lot easier to work around lack of final classes, e.g. with private constructors or—I haven't used this, but I imagine—a runtime check like this.constructor === MyClass.
  • Google's Dart language (as a point of reference) addresses them in two different ways, a final class modifier and a @nonVirtual method annotation.

(3)

Ryan also wrote:

The general consensus on final classes was that from a type perspective, interactions between a base class and its derived classes are a complex interplay that can't be accurately described by providing a few keywords. By that measure, final of any form would be a "half measure" that doesn't really completely solve what is really an extremely complex problem.

It's hard to see how any set of modifier keywords in any language could be said to "completely solve" the "extremely complex problem" of the "interactions between a base class and its derived classes." As others have pointed out, by this standard, modifiers like override and protected would be condemned as "half measures" and not implemented. It's a heavy-handed argument that is hard to take at face value.

(In Dart, by the way, @override and @protected are annotations—similar to decorators—not keywords, and I'm in a thread right now about what it would take to make protected a language keyword, which would be slightly less clunky in certain ways. Part of the complexity being raised is that any core language feature, for philosophical reasons, would have to be implemented in the runtime, too, with runtime checks. There isn't the same split of TypeScript and TC39 being different parties, and the Dart team has expressed low-priority willingness to eventually bring protected into the language, maybe with some modifications, but there is a similar sense of "you can't have nice static things because that sounds like something the runtime could get in on." Different languages seem to have different versions of this. Anyway, it could be worse, TypeScript could be refusing to implement protected, or the definitely-wouldn't-be-added-today private.)

Runtime enforcement should not be a major consideration, IMHO. The point of features like this is to aid programmers working together and reduce bugs. I realize there is the relationship with the evolution of ECMAScript/TC39 to consider, but it's so ironic, considering that TypeScript is all about adding static guarantees to your code that are utterly unchecked at runtime.

(I know I keep bringing up Dart, but it's just a really interesting language to compare. Did you know that in Dart, operators like ! and as emit runtime checks?? There is a concept of "runtime soundness," where if there are holes in the static type system, they must be plugged at runtime. This is partly because Dart doesn't just compile to JavaScript, it can be AOT-compiled to machine code. It is very hard in Dart for your static types and your runtime types to differ at all—even type parameters are reified at runtime—while in TypeScript, it is super easy; you can set up a static fantasy land if you want, and it will never be checked. So that's part of why it's ironic.)

I sort of understand the argument that class features are the domain of ECMAScript, while type features are the domain of TypeScript, but... we have override. And TC39 doesn't seem to be working on final? TypeScript implementing something here might even lead the way as far as TC39.

Update: TC39 discussion / Suggestion to use decorators!

I just found this: TC39 Discourse: Final classes

The current thinking seems to be, final classes (and methods) can now probably be implemented with decorators. They'll see if that takes off.

I would argue this puts the ball in TypeScript's court as far as how to check these decorators statically. Or, why not have a compiler flag where the "final" keyword adds a decorator? Or, to save work, don't bother emitting decorators in the first version; see if people are dissatisfied with just static enforcement. I just want squiggles in my IDE.

IMHO, it doesn't make sense for TypeScript to wait for TC39 to consider adding a final keyword to the language, when TC39 only needs to be concerned with runtime enforcement, and they are waiting to see if decorators solve that problem. At the end of the day, there's no uncertainty about what the semantics of final would be, anyway, I don't think, so no downside in TypeScript moving forward, whether it's a keyword or a decorator.

dgreensp avatar Apr 27 '24 23:04 dgreensp

Decorators kinda solve the problem, but not fully, already made a class decorator (definition, how it works), not perfect though, but gets the job done.

  @Final
  class Foo<T> {
    foo: T;

    constructor(foo: T) {
      this.foo = foo;
    }
    someFoo(): T {
      return this.foo; 
    }
  }

  class SubFoo extends Foo<string> {
    constructor(foo: string) {
      super(foo);
    }
  }


const _ = new SubFoo('subbedFoo');

This will cause a runtime TypeError: Cannot inherit from the final class at Foo ... at SubFoo ... (The error message is not perfect yet).
Wouldn't it be better to error out at compile time ?

  final class Foo<T> {
    foo: T;

    constructor(foo: T) {
      this.foo = foo;
    }
    someFoo(): T {
      return this.foo; 
    }
  }

  class SubFoo extends Foo<string> {} // You can't even do this, TS will complain 
   

Same for methods.

rccyx avatar May 04 '24 14:05 rccyx

I would also like to have the final keyword added to the language. It can be mostly done using decorators now, but at the cost of runtime errors. Wasn't typescript supposed to protect us from them by having a compilation step? Additionally, I don't see how this can be complicated to add, since it's not that different from private and such.

I don't know how the rest feels about this, but I find myself wanting to use the missing feature in around 80% of the projects I participate.

The issue is not locked to allow members of the community to continue adding feedback. With enough feedback and compelling use cases, issues can be reopened.

Hey @mhegazy, based on the feedback in this issue got over the years, it looks like there is a lot of people that would be happy having it. Isn't worth considering removing the won't fix label and engage in discussions again?

neeko-cat avatar Jul 15 '24 19:07 neeko-cat

Any update ?

Ayfri avatar Sep 17 '24 22:09 Ayfri

Any update ?

We've been ignored, my friend.

neeko-cat avatar Oct 14 '24 21:10 neeko-cat

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

This comment, and all the argumentation preceding it about it being "extremely uncommon" to inappropriately override classes or methods, runs contrary to the well studied problem of the Fragile Base Class problem. It's ironic that in this post the fragility of classes was cited as an argument against introducing the final keyword. This is a perfect inversion of the truth. Fragility of classes is exacerbated, if not fundamentally caused by, the fact that final is not the default behavior, and (if final is supported at all) must be opted out of. The alternative, which is supposed to help fix the fragility of classes, is to require a keyword for non-final classes or methods, such as C# requiring a method to be marked virtual in order to be overridable (C# makes overridability the default for classes however).

I'm not suggesting TypeScript make classes and methods final by default and introduce something like an overridable keyword, only because that's a breaking change (it's just too late to consider that, for better or worse). I bring it up to point out that the result of careful study of the fragility of classes has produced the exact opposite conclusion argued here, that finality should not only be an option but the default option. Since it's too late to make it the default, at least we should make it an option.

Any time someone argues, "just add a comment", they're fundamentally misunderstanding the point of static typing. That argument can be made enough to take us all the way back to assembly language. After all, you can just add comments indicating that a memory address holds a specific variable with a human readable name. The reason we introduce tools for this is to automate it. Responding to, "can we add final" with, "just don't subclass it then", is responding to, "can we put a guard in for this mistake" with, "just don't make the mistake". Putting in a guard is how we "just don't make" the mistake! We automate things because manual processes are tedious and error prone. In the context of TypeScript, "just add a comment" is essentially saying, "just write JavaScript".

Furthermore, the literature on the Fragile Base Class problem, which includes published research papers, thoroughly refutes the claim that the mistake is "extremely uncommon". It is, rather, so common that it has been christened with a proper name and made the subject of rigorous research. The comment, "I have never tried to subclass something only to find out it's final" is an ironic justification for it not being possible to mark something as final (that would explain why that guard has never been encountered). The reason for never encountering this is either because it's not supported in the language, or it's supported but not used appropriately by class authors.

The correct question to ask is, "have I ever successfully subclassed something I was allowed to, only to find out later I shouldn't have?" The answer, "I have tons of OOP experience and that's never happened" just suggests a failure to properly identify the mistake or do root cause analysis to tie bugs back to it. Essentially every large OOP codebase I've worked on is rife with deep inheritance hierarchies that significantly abuse subclassing and overriding.

TypeScript should support final on both classes and methods so that TypeScript developers can then start adopting the practice of marking every class and method final by default (except where redundant) and removing final only when it becomes necessary. If that practice gets widely adopted, then maybe classes will stop being so fragile to begin with. This is one of the most important lessons the OOP community learned the hard way from decades of hard empirical evidence, and it would be a shame to have to repeat that history.

aetherealtech avatar Nov 05 '24 00:11 aetherealtech