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

@hk0i I don't agree neither, the purpose of typescript is to structure the code and therefore providing the tools to do so. We do not HAVE to use final in Java, we typically use it when we know that extending a class or method could lead to introducing side effects (or for any other safety reason).

Relying on the current ES6 solutions adding a runtime mutability check (saying using Object.seal or Object.freeze) makes you loose the benefit of having errors directly when you type your code (despite it could easily be done using this decorator).

Xample avatar Mar 19 '18 07:03 Xample

@TheColorRed yes… and in typescript we have a distinction for local and class variable.

  • readonly for a class variable
  • const: for any other variable

None of them would be accurate for method or class. Overriding a method does not mean we are redefining it (think in virtual methods in C++), we just define a method will will be primary be called before the super one (which we can call using super).

Xample avatar Mar 19 '18 07:03 Xample

@niokasgami perhaps the naming is not really a problem as we will still understand that Object.seal applied to… an object while sealing a class and a method to the structure itself.

TL;DR:

  • preventExtensions would be a good explicit name to prevent extending classes
  • preventOverrides would be a good candidate name to prevent overriding classes BUT: seal is widely used in C#, shorter and has the same expected behaviour.

By the way I forgot to mention there is also Object.preventExtensions() Differences can be seen here

reading

  • always possible… who wants a write only variable ?

updating and deleting

  • prevent redefining a deleting a variable: readonly for a class member, const (for any other)
  • prevent redefining a method: nothing prevents you to do (within a class method) this.aMethod = ()=>{}. Should methods be readonly as well to prevent such hacks ? same for delete this.aMethod

creating

  • only applies to object or as we are talking here about structure: class as the class defined the members of the object, typescript implicitely already prevents from creating new properties on the fly… for instance this.unKnownProperty = "something"ts will raise a compilation time error TS2339 as expected.

extending

  • only applies to classes, we are not doing anything on the object itself yet… (unlike the creating which is at runtime). This is where final or seal would be relevant. The question is how to stay consistant wit the freeze, seal and preventExtensions of ES6 ? (if we have to). Extending a class, mean we prevent creating another class from this class. We can then read it but not delete it (who deletes class anyway). The question is not the "update" column. Is a final class updatable ? What is a class updatable ? My guess is yes… but then the update would be to implement this class (understanding the interface of the class) ? Implementing another class should always be possible… but it's not related to updating the initial class. Well… perhaps they simply came to the same questions writing c# and decided that seal was the good keyword.

overriding

  • prevent overriding the current method in a extending class. Again, we are not overwriting anything yet as we are talking about a definition (method within a class). So prevent creating, allow reading, allow updating (we could prevent updating the method or deleting it using readonly if it was applicable to methods as well). Best naming ? preventOverrides ? or again seal as it is used in C#

BONUS: As sealing a method is usually to prevent people overriding mandatory super code, I made the proposal of forcing people to call the super method (the same behaviour as for the constructor but for any method) don't hesitate to vote up if you think it would be useful.

Xample avatar Mar 19 '18 09:03 Xample

Don't get me wrong, I'm not against this. I'm very much for it. I'm just trying to get behind Microsoft's paradoxical mindset of why it shouldn't be a feature, which is essentially saying that because it's not a JavaScript feature it cannot be a TypeScript feature.

... If I'm understanding correctly.

hk0i avatar Mar 20 '18 03:03 hk0i

@hk0i Generics, readonly, and many other features are not a JavaScript features, but they are still added into TypeScript, so I don't think that is the reason...

TheColorRed avatar Mar 20 '18 14:03 TheColorRed

TypeScript only shies away from features which require generating code in a non-straightforward way. Generics, readonly, etc are purely compile-time notions which can be simply erased to produce the generated output, so they’re fair game.

pelotom avatar Mar 20 '18 15:03 pelotom

final can be "erased" at compile time too, so why doesn't that make it "fair game"?

TheColorRed avatar Mar 20 '18 15:03 TheColorRed

🤷‍♂️

pelotom avatar Mar 20 '18 15:03 pelotom

@TheColorRed I think this more or less this either they have other priority to integrate. Or they unsure how predictable this new keyword could work on compile/ coding time. if you think about it the design of final keyword can be extremelly vague. final could be used a lots for many purpose. As you can see from the Jsdoc documentations you can use the tag "@final" which tell the jsdoc interpreter that this variable is frozen thus readonly.

here a design clash. Readonly is aplicable on variable and getter if I recall which "froze" the variable and make it readonly and final make it final thus readonly as well.

this can cause confusion to the programmer who is unsure if they should tag their variables final or readonly.

UNLESS we reserve this keyword exclusively for class and method declarations, I think the behavior or final would clash with readonly.

I think instead of sealed (which can clash with object.seal) or final (which this purpose design clash readonly keyword) we could go with a more "direct" way to name and design it.

take note this merelly a "idea" of a behavior who is similar but in same time different from the C# behavior? I took some inspirations from how C# is normally nonOverridable and then you have to say that this method is virtual.

` namespace Example {

export class myClass {

    constructor(){}

    // Make the func non ovveridable by inheritance. 
    public unoveridable myMethod(){

    }
    
    public myMethodB(){

    }
}

export class MyClassB extends myClass {

    // Nope not working will throw an error of an nonOverridable error
    myMethod(){
        super.myMethod();
    }

    // Nope will not work since unoverridable.
    myMethod(){

    }

    // Design could be implemented differently since this could complicate  ¸
    // the pattern of typescript
    public forceoverride myMethod(){
      // destroy previous pattern and ignore the parent method thus a true ovveride
    }

    // Yup will work since it's still "virtual".
    myMethodB(){
        super.myMethodB();
    }
}
// Can extend an existing Parent class
// Declaring an unextendable class make all is component / func nonOverridable by 
// inheritance. (A class component can still be overwritten by prototype usage.)
export unextendable class MyFinalClass extends Parent {

    constructor()

    // nonoverridable by default.
    public MyMethod(){

    }
}
// nope throw error that MyFinalClass is locked and cannot be extended
export class MyChildClass extends MyFinalClass{}

}`

Edit : I didn't include Variable and get since readonly already exists.

niokasgami avatar Mar 21 '18 06:03 niokasgami

@mhegazy Please consider reopening this issue. The community response seems to be overwhelmingly on the side of adding a final keyword, like Java (final), C# (sealed, readonly), PHP (final), Scala (final, sealed), and C++ (final, virtual) have. I can't think of a statically typed OOP language that doesn't have this feature, and I haven't heard a convincing argument for why TS doesn't need it.

bcherny avatar Mar 25 '18 19:03 bcherny

@bcherny @mhegazy I completely agree with the above. I cannot see any well argued reason why final can't just be another compile-time constraint, like most of the syntactic sugar we see in TypeScript - let's face it, static typing, generics, access modifiers, type aliases, interfaces...ALL SUGAR! I get that the TypeScript team probably want to focus on taking the language in other directions, but seriously, this is OOP 101... this should have been though about a long time ago, when TypeScript was still very young!

MrMatthewLayton avatar Mar 26 '18 09:03 MrMatthewLayton

@mhegazy may I refer you back to an early comment you made on this issue?

a class with private constructor is not extendable. consider using this instead.

At the time of writing this comment has been down-voted 21 times. Clearly this is NOT WHAT THE COMMUNITY WANT AS A SOLUTION!

MrMatthewLayton avatar Mar 26 '18 09:03 MrMatthewLayton

wow, got a lot of feedback about this. I can't understand why no interest to implement

Zorgatone avatar Mar 27 '18 17:03 Zorgatone

Lots of really unproductive complaining going on here. Please don't just show up to voice frustration - we are allowed to make decisions here and the community is allowed to give their feedback, but just idle gnashing of teeth is not going to change anyone's mind. Please be specific and actionable; we're not going to be convinced by people just showing up to say DO THIS FEATURE NOW.

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.

Some points were considered when we reviewed this last time

  • CLASSES ARE A JAVASCRIPT FEATURE, NOT A TYPESCRIPT FEATURE. If you really feel like classes are completely useless without final, that is something to take up with the TC39 committee or bring to es-discuss. If no one is willing or able to convince TC39 that final is a must-have feature, then we can consider adding it to TypeScript.
  • If it's legal to invoke new on something, that has a one-to-one runtime correspondence with inheriting from it. The notion of something that can be new'd but not super'd just doesn't exist in JavaScript
  • We are trying our best to avoid turning TypeScript into an OOP keyword soup. There are many better composition mechanics than inheritance in JavaScript and we don't need to have every single keyword that C# and Java have.
  • You can trivially write a runtime check to detect inheritance from a "should-be-final" class, which you really should do anyway if you're "worried" about someone accidently inheriting from your class since not all your consumers might be using TypeScript.
  • You can write a lint rule to enforce a stylistic convention that certain classes aren't inherited from
  • The scenario that someone would "accidently" inherit from your should-be-sealed class is sort of an odd one. I'd also argue that someone's individual assessment of whether or not it's "possible" to inherit from a given class is probably rather suspect.
  • There are basically three reasons to seal a class: Security, performance, and intent. Two of those don't make sense in TypeScript, so we have to consider the complexity vs gain of something that's only doing 1/3rd the job it does in other runtimes.

You are free to disagree with all of these, but please bring some actionable and specific feedback about how the lack of final is harming your ability to effectively use JavaScript classes.

RyanCavanaugh avatar Mar 27 '18 18:03 RyanCavanaugh

haven't heard a convincing argument for why TS doesn't need it

Just a reminder that this is not how it works. All features start at -100. From that post

In some of those questions, the questions asks why we either “took out” or “left out” a specific feature. That wording implies that we started with an existing language (C++ and Java are the popular choices here), and then started removing features until we got to a point where we liked. And, though it may be hard for some to believe, that's not how the language got designed.

We have a finite complexity budget. Everything we do makes every next thing we do 0.1% slower. When you request a feature, you're requesting that every other feature become a little bit harder, a little bit slower, a little bit less possible. Nothing gets in the door here because Java has it or because C# has it or because it'd only be a few lines of code or you can add a commandline switch. Features need to pay for themselves and for their entire burden on the future.

RyanCavanaugh avatar Mar 27 '18 18:03 RyanCavanaugh

@RyanCavanaugh While I'm not sure I agree with the decision, I do appreciate the really thoughtful and detailed response, and for your taking the time to write it. I get that you want to keep the language lean - it's good to reflect on whether features that other popular languages have are really valuable, or just common.

bcherny avatar Mar 27 '18 18:03 bcherny

@RyanCavanaugh

I don't think the point here, in this forum is .. "effectively use JavaScript classes."

Sorry, I can not resist, and just add to the "unproductive complaining going on here": the final keyword is usefull for all the reasons explained, in detail, and with arguments by others.

alpapad avatar Mar 27 '18 18:03 alpapad

We are trying our best to avoid turning TypeScript into an OOP keyword soup. There are many better composition mechanics than inheritance in JavaScript...

Like when you use final to enforce composition over inheritance in (insert not typescript language name here) 😈 (Sorry, I couldn't resist)

But more to the point, it seems like TS intends to mostly be a compatibility layer to introduce "today's JavaScript now" or something to that effect (a la Babel) with the exception that it adds some additional type checking.

I think the gist of the counter argument for implementing this is that if you want another language's features, use the other language instead. If you want JavaScript, use JavaScript. If you want TypeScript, use that.

I know Kotlin can compile to JS and has a lot of the features that I think the people here would enjoy so that is something that might be useful to look into. I think it does add some JS library as a dependency though (I haven't tried it myself).

The main takeaway being that if you're not happy with TypeScript, don't use it.

hk0i avatar Mar 27 '18 18:03 hk0i

@RyanCavanaugh

On the points you raised above...

CLASSES ARE A JAVASCRIPT FEATURE, NOT A TYPESCRIPT FEATURE. If you really feel like classes are completely useless without final, that is something to take up with the TC39 committee or bring to es-discuss. If no one is willing or able to convince TC39 that final is a must-have feature, then we can consider adding it to TypeScript.

I've been following TypeScript since 0.7 and back then, IIRC it was targeting ES3-ES5. Classes were definitely a TypeScript feature back then. The same argument applies to decorators - they're on the cards for ES, but they're already here in TypeScript as an experimental feature.

As a community, we're not arguing that the TypeScript compiler must somehow emit a JavaScript class that's final . A compile-time check would suffice, in the same way that compile time checks for access modifiers suffice; after all, they're not JavaScript features either, but TypeScript still makes them possible.

If final did become an ES feature, then presumably you could refactor that bit of the emitter when targeting ES* to output final appropriately (In the same what you did for classes, when they were introduced in ES6)?

If it's legal to invoke new on something, that has a one-to-one runtime correspondence with inheriting from it. The notion of something that can be new'd but not super'd just doesn't exist in JavaScript

Again, I don't think the community are expecting you to magic something up here to enforce final at runtime. As you've accurately stated, it "doesn't exist in JavaScript", but as mentioned, a compile-time constraint would suffice.

We are trying our best to avoid turning TypeScript into an OOP keyword soup. There are many better composition mechanics than inheritance in JavaScript and we don't need to have every single keyword that C# and Java have.

It's a fairly well known phrase in the software development community as a whole: "Favour composition over inheritance", however "favour" doesn't mean don't use inheritance as a blanket statement. Sure, you don't need every single keyword that C# and Java have, but you must have had a rationale for allowing abstract classes (which by the way "doesn't exist in JavaScript"), so why not final classes?

You can trivially write a runtime check to detect inheritance from a "should-be-final" class, which you really should do anyway if you're "worried" about someone accidently inheriting from your class since not all your consumers might be using TypeScript.

The same could be said for C# and Java, but I don't need runtime checks because I have sealed and final to do that for me at the compiler level.

If not all my consumers were using TypeScript, I'd have a lot more to worry about than just inheriting from a final class; for example, access to private or protected members, no static type checking, or the ability to construct an abstract class.

Should our code really be littered with runtime checks for all these things (some of which aren't even possible I might add) just to make sure our non-TypeScript consumers are as safe as possible?

You can write a lint rule to enforce a stylistic convention that certain classes aren't inherited from

This would imply that whoever is consuming your code is running the linter, so it's still not really a proper solution; it's a workaround.

The scenario that someone would "accidently" inherit from your should-be-sealed class is sort of an odd one. I'd also argue that someone's individual assessment of whether or not it's "possible" to inherit from a given class is probably rather suspect.

Good/Great developers think about their rationale for doing something, like extending a class. Any less than that and you end up with a "but it works" mentality, without really understanding why.

Asking a question that starts with can I usually tends to have a more definitive answer than questions that start with should I.

There are basically three reasons to seal a class: Security, performance, and intent. Two of those don't make sense in TypeScript, so we have to consider the complexity vs gain of something that's only doing 1/3rd the job it does in other runtimes.

Arguably I'd say that TypeScript would actually fulfil two of these reasons: Security and intent, however if this was implemented purely as a compile time check, then it could only do this at the compiler level, rather than, as you rightly point out, at the runtime level.

I don't think that not having final is harming my ability to effectively use JavaScript classes, nor are JavaScript classes unusable without it. I feel that final is more on the side of a "nice to have" feature, rather than a "necessary" feature, but then the same could be said for many of TypeScript's features.

I think the main gripe here is that TypeScript allows us to create abstract and open classes, but in terms of inheritance and polymorphism it doesn't allow us to paint a complete picture in an elegant and expressive way.

Hiding the constructor isn't what the community want because this takes semantic and expressive value away from class implementations, and once again, because access modifiers are a "nice to have", this can't even be enforced at runtime; essentially a "doesn't exist in JavaScript" situation.

As a developer I have many hats; at the moment I have a C# hat, a Kotlin hat and a TypeScript hat.

  • With my Kotlin hat on, I don't have to worry about final because classes are final by default.
  • With my C# hat on, I apply sealed as a matter of habit, forcing my consumers to ask can I rather than asking should I. More often than not, C# classes should actually be sealed and it's often overlooked.
  • With my TypeScript hat on, I have to hide the constructor as a workaround, because in my (and the communities) opinion, the language lacks something useful.

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"?

MrMatthewLayton avatar Mar 28 '18 10:03 MrMatthewLayton

@RyanCavanaugh Hum I do understand your points

I think mostly it's was an misunderstanding (I guess from how we explained)

@series0ne summary really well that our intentions wasn't too complicate the typescript output by asking to create final class in JS (heck this would be an train wreck to do so) but to just create extra rules for tell peoples : Nope you can't do that. and it's tell the user of the API that they probably shouldn't mess with those class (for stability, security reason etc) ALL on the typescript files/compiler NOT on the output.

Do I think it's would be nice to have this feature : yes it's nice to have more fast way to do some technique.

Is it TRULY needed? Not really this could be something considerate minor and shouldn't be a priority if the Typescript team can afford to implement this extra then it could be nice to have.

I do see that the final/sealed keyword could complicate a LOTS some aspect especially : Bug fix, Patch, change of behavior.

if I explain this, I could totally see an abusive use of final by locking ALL the class from being extended. Provoking IMO a big pain in the a** to deal with. I don't want to use an API where I am locked to do any change to the user class by inheritance because they was to paranoid because of "security".

This would mean I would have to go using prototype then alias or override this class just for the sake to be able to change this class behavior for fit my needs. this would be annoying especially if I just want to add extra functionality to the said class and don't want to go with a destructive workflow.

After this just my though I might misunderstand myself the situations right now so be free to explain it to me :)

niokasgami avatar Mar 29 '18 04:03 niokasgami