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

If I'm not mistaken adding final could help to avoid hassle with 'myObj' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'MyClass' errors when working with generics because I could make MyClass final and therefore guarantee there aren't any other subtypes. Not 100% sure but I think that's how you can solve this issue in Java.

JonasDoe avatar Aug 26 '20 10:08 JonasDoe

We have the same stuff, we are making a base Component in angular that a lot of other packages can or need to extends as there base. In that we have things like ngOnChanges or even ngOnInit of angular that only the base class should implement and subclasses shouldn't override these but really implement the ngOnInitReal (or what eer we call it) so we are fully in control when that is called and with what. Because we can't control this we can only do this through documenation. If one component maker doesn't read this its component can break, or it needs to copy a lot of code from our base to do the same thing..

So without final methods we can't really make a rock solid api contract.

jcompagner avatar Oct 08 '20 11:10 jcompagner

did someone mention

class Fancy {
    readonly secureFoo = (message: string) => {
        console.log(message);
    }
}

Schokokex avatar Dec 02 '20 23:12 Schokokex

did someone mention

class Fancy {
    readonly secureFoo = (message: string) => {
        console.log(message);
    }
}

While you can do this, there are some differences. For example, each instance of the class will have its own copy of the function, as opposed to only the prototype having the function that everyone uses.

sam-s4s avatar Dec 03 '20 21:12 sam-s4s

This is an issue I ran into. Such simple code sample cannot be compiled. final keyword would PERFECTLY solve it:

abstract class Parent {
    public abstract method(): this;
}

class Child extends Parent {
    public method(): this {
        return new Child();
    }
}

Type 'Child' is not assignable to type 'this'. 'Child' is assignable to the constraint of type 'this', but 'this' could be instantiated with a different subtype of constraint 'Child'.

Playground

I ran into this exact problem, and I don't know if there is a good solution. SO post that sorta gets at this idea, but without a good solution (imo): https://stackoverflow.com/questions/34095437/typescript-self-referencing-return-type-for-methods-in-inheriting-classes

ekilah avatar Dec 10 '20 00:12 ekilah

I apologise for commenting on a closed issue thread, but I too would like to see a final keyword for class methods. I'm failing to understand the arguments against it to be honest.

In my case, the following update and render methods MUST NOT be overridden by a subclass, those methods will invoke the onUpdate and onRender methods in their own time to allow a subclass to do its work:

abstract class Node {
    public render(): void {
        this.onRender()
    }
    public update(): void {
        this.onUpdate()
    }
    protected abstract onRender(): void
    protected abstract onUpdate(): void
}

Now, the only way I can currently enforce that is to do something along these lines:

abstract class Node {
    public render(): void {
        if (this.constructor !== Node) {
            throw new Error()
        }
        this.onRender()
    }
    public update(): void {
        if (this.constructor !== Node) {
            throw new Error()
        }
        this.onUpdate()
    }
    protected abstract onRender(): void
    protected abstract onUpdate(): void
}

Clearly not a nice thing to be doing. Using a final keyword here would make much more sense:

abstract class Node {
    public final render(): void {
        this.onRender()
    }
    public final update(): void {
        this.onUpdate()
    }
    protected abstract onRender(): void
    protected abstract onUpdate(): void
}

Just my two cents.

simon-robertson avatar Dec 23 '20 15:12 simon-robertson

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.

@RyanCavanaugh or anyone else, I scanned through the whole thread, but I couldn't find anyone else referencing this. How would you trivially do this in javascript/typescript at runtime? I'm not exactly sure.

kurkowski avatar Feb 02 '21 00:02 kurkowski

@kurkowski, I think @RyanCavanaugh is being tongue-in-cheek. He’s saying you can do something like:

export class Options {
}

// Capture the current prototype in case if the consumer replaces the prototype to try to bypass our check.
const capturedOptionsPrototype = Options.prototype;

export function useOptions(options) {
  if (Object.getPrototypeOf(options) !== capturedOptionsPrototype) {
    throw new Error(`You must pass an instance of precisely Options.`);
  }

  // Do things here…
}

And that, if you want to prevent people from subclassing your final classes, you should write that everywhere you would consume Options.

I don’t understand his point because that is not really a maintainable approach. I think he is saying that we should be fine if people use duck-typing and accept the old Pythonic way of doing things—and not care if other people create and pass around subclasses of classes that were never designed to be safely extended. This is similar to how TypeScript won’t implement proper nominal typing.

binki avatar Feb 02 '21 00:02 binki

@binki, I think that's actually the answer right there. You can get a "final" class by doing what you suggested, but put it in the constructor of the parent class.

export class A {
  constructor() {
    if (Object.getPrototypeOf(this) !== A.prototype) {
      throw new Error('Cannot extend this class.');
    }
  }
}

class B extends A() {}

let a = new A(); // works just fine
let b = new B(); // error is thrown

I think a "final" method would be a little trickier. You could do the same check in the method, so a child class would error on calling "super". However, if the child method never called super, I don't know if the parent can do anything about it.

kurkowski avatar Feb 02 '21 01:02 kurkowski

@kurkowski But if TypeScript had a final/sealed feature, it could enforce those restrictions at compile-time when compiling TypeScript code. Ideally, these checks would be omitted/unnecessary at runtime. Also, checks in constructors can be bypassed by using things like Object.create().

TypeScript isn’t about trying to prevent people from writing JavaScript to bypass typings at runtime. It is about opting into type-checking by compiling TypeScript code and being alerted to issues such as attempts at extending classes and overriding members which were not designed for that purpose (indicating you’re likely doing something unsupported or which will introduce bugs in the future even if it works now). And also about reducing the amount of runtime checks that need to be done (because there is no need to check that typeof(x) === 'string' since the TypeScript compiler will simply prevent you from accidentally setting something other than a string onto x). If we find ourselves manually throwing errors in the constructor when attempting to extend a class, we’re writing code that we shouldn’t need to write in the first place and which has already been solved by typing systems which support the concept of final/sealed classes.

binki avatar Feb 02 '21 01:02 binki

I would also add, that the same way we have public, protected and private access modifiers, which do not transpile at all to JavaScript and do not prevent unintended access in JavaScript, we should be able to support final / sealed as the use case is clearly there.

doronguttman avatar Feb 02 '21 02:02 doronguttman

@binki, yeah, completely agree. I'm all for compile-time checking over runtime. I was just trying to see how something could be done during runtime because it wasn't clear to me.

kurkowski avatar Feb 02 '21 02:02 kurkowski

Now that the override keyword is slated for 4.3 — because it is useful to have discipline about overrides in large codebases, as the Google team attests — I think some of the arguments against being able to mark a method as final (meaning non-overridable) are invalid.

Here are some of the reasons for rejecting final methods given by (I believe) members of the TS team:

(1) Final (non-overridable) methods are basically the same language feature as final (non-extendable) classes. They should be discussed together. Reasons to implement or not implement one apply to the other. The belief in this proposition is why I must post here, in this thread, and not in an issue dedicated to final methods. FWIW, they seem like totally different language features to me. In particular, I don't care about final classes. We might have to agree to disagree on this one.

(2) It's not useful, valuable, or in scope for TypeScript to get involved with the contract between superclasses and subclasses. The usefulness and suitability of override (which asserts that a method is an override) invalidates this, not to mention the fact that we have keywords like protected providing similar OO contract enforcement. There is not that much semantic category difference between "this method must override something" and "nothing may override this method."

(3) The purpose of the final keyword in languages like Java is basically performance. No, the primary purpose is for correctness by enforcing a contract. Some methods are meant to be overridden by subclasses, and some are not, just as a public member is meant to be accessed outside a class, while a private member is not.

(4) This feature is in scope for ECMAScript, so we can't just do our own thing. This actually sounds valid, if we're really talking about final methods in particular, and if there is a potential for divergence of behavior (as with decorators). (So override is not in scope of ECMAScript, but final for methods is?) It's true that final has runtime implications and guarantees in Java, and perhaps it could in JavaScript, like the way private fields are actually enforced by the engine, though strong guarantees about class inheritance don't seem that useful for JavaScript performance or security, I mean aren't classes basically a sort of built-in syntactic sugar for prototypes anyway? Blocking overriding at the prototype chain level would be as different a feature from what we're talking about here as private fields vs. TypeScript's private, in terms of the mechanics of it. Or, ECMAScript's final methods could just end up being the same as TypeScript's, plus runtime enforcement. How much room for divergence of behavior is there really?

The only logical reason for not implementing final methods that I can come up with is (4), namely that ECMAScript could introduce a final keyword on methods of its own, that is incompatible with TypeScript's.

Obviously, no amount of logic forces the wonderful TypeScript team to go and immediately implement a feature like final methods. They are busy and can do whatever they want. I just wanted to lay out the argument and maybe clear out some distracting cobwebs from the conversation.

dgreensp avatar Feb 23 '21 20:02 dgreensp

I'm a big fan of final/sealed in every language and the stronger contract it allows, but I think the existing support is nearly sufficient - the example in TypeScript handbook | Class Decorators:

function sealed(constructor: Function) {
  Object.seal(constructor);
  Object.seal(constructor.prototype);
}

@sealed
export class CantSubclassMe {
  ...
}

The only downside I see to this is that it doesn't provide compile-time enforcement, but it does provide run-time enforcement.

**** EDIT **** (180 degree change)

Oops, I made the mistake of thinking this would work as it reads without testing it and reading the fine print/thinking about it. Turns out the @sealed decorator described in the handbook doesn't do much. If you freeze the prototype, you can prevent prototype modification, but due to prototype chaining sealing a constructor or prototype doesn't do much.

export function sealed(constructor: Function) {
  Object.seal(constructor); // Doesn't seem to do much - not sure why it's included
  Object.freeze(constructor.prototype); // Object.seal doesn't protect much, but Object.freeze does
}

@sealed
class A {
  method() {
    console.log('A.method()');
  }
}
class B extends A { }
class C extends A {
  method() {
    console.log('C.method()');
  }
}

/** Same as class A, but prototype is modified in test */
@sealed
class AA {
  method() {
    console.log('AA.method()');
  }
}

describe('@sealed', () => {

  it('does not prevent subclassing a class', () => {
    const b = new B();
    expect(b).toBeInstanceOf(B);
  });

  it('does not prevent overriding methods in subclasses', () => {
    const c = new C();
    expect(c).toBeInstanceOf(C);
  });

  it('does prevent replacing methods in the same prototype', () => {
    expect(() => {
      AA.prototype.method = () => { console.log('prototype replaced AA.method()'); };
    }).toThrowMatching(e => e instanceof TypeError);
  });

  it('does prevent replacing methods in a constructed object', () => {
    const a = new A();
    expect(a).toBeInstanceOf(A);

    expect(() => {
      a.method = () => { console.log('instance replaced A.method()'); };
    }).toThrowMatching(e => e instanceof TypeError);
  });

});

So, it turns out that existing language features DO NOT handle this case.

johncrim avatar Mar 07 '21 22:03 johncrim

I put a little more work into this decorator to make it work. It does provide runtime enforcement that a subclassed @final class cannot be instantiated. It does not provide compile time checks or method level enforcement.

This gist provides more complete code (tests, etc), but here's the key part:

export declare interface Type<T> extends Function {
    new (...args: any[]): T;
}

function preventSubclassing<T>(constructor: Type<T>): Type<T> {
  const newCtor = function (...args: any[]): T {
    if (new.target.prototype !== constructor.prototype) {
      throw new TypeError(`${constructor.name} cannot be subclassed`);
    }
    return new constructor(args);
  };

  // copy prototype so instanceof operator still works
  newCtor.prototype = constructor.prototype;
  return newCtor as unknown as Type<T>;
}

/**
 * Class decorator that prevents type modification and extension. If the decorated
 * class is subclassed, a `TypeError` is thrown when the subclass is constructed.
 *
 * The name `@final` is used instead of `@sealed` b/c in Javascript, sealing
 * protects against object modification (not type extension).
 */
export function final<T>(constructor: Type<T>): Type<T> {
  const newCtor = preventSubclassing(constructor);
  Object.seal(newCtor);
  Object.freeze(newCtor.prototype);
  return newCtor;
}

Usage:

@final
class A {}

class B extends A { }

const b = new B(); // throws TypeError('A cannot be subclassed');

I'm not certain that it's production ready yet - consider it a concept. For example, right now there are 2 calls to new when a decorated class is instantiated, and I'm not sure if that's a problem or not (does it result in a wasted allocation?).

I would still love to see first-class typescript support for a final keyword that seals classes or methods, but it would be ideal to have support for both compile and runtime checks.

johncrim avatar Mar 08 '21 15:03 johncrim

Notably absent from this discussion is that final classes and final methods (independently) allow TS to analyze assignments in methods called in the constructor as if they were written directly in the constructor.

With strictPropertyInitialization: true, the following class declaration is an error (TS2564: Property 'someProperty' has no initializer and is not definitely assigned in the constructor.):

class SomeClass {
  someProperty: number;

  constructor() {
    this.setup();
  }

  // or init()
  setup() {
    this.someProperty = 0;
  }
}

despite the fact that the following compiles without error:

class SomeClass {
  someProperty: number;

  constructor() {
    this.someProperty = 0;
  }
}

The reason is that TS doesn't know whether any subclass of SomeClass redefines setup(), and thereby removes the assignments.

The workarounds, which don't provide assurance that setup() won't be overridden, are:

  1. assert someProperty as non-null (unsafe),
  2. add undefined to the type of someProperty/make someProperty optional (clunky, propagating, and extraordinarily weak)
  3. copy over all assignments made in setup() to the constructor or the declarations (messy).

I'm sure most of us see all of these as both bad practice and difficult to maintain.

Adding the final keyword to either SomeClass or setup(), though, would clearly convey intent, and provide the necessary protection. As a result, the type system would have sufficient information to deduce that someProperty is actually defined in the constructor.


I suppose many developers overlook that methods called in the constructor can be overridden, and rely on behavior defined in the "base class." In particular, in the above example, setup() could perform logic that's critical to the initialization of the object. It could instead be reset(), a method to roughly restore the class to its initial state. In either case, the method's exact behavior could be used as an assumption unknowingly in the constructor.

pihart avatar Mar 31 '21 00:03 pihart

@mhegazy There is no question this keyword makes sense and is useful both on class and methdo level - and I do not talk about runtime optimization here. The suggestion to write comments to inform the user of a class is just ridiculous - I just need this keyword to restrict user of my class (myself) doing dumb things with it like overriding a method not meant to be overridden. The keyword does not introduce any complexity for the end user of the language. It is a strictly optional check for the compiler to do when overriding a method. Emit a warning/error - thats all.

I suggest you put this on the roadmap along with a bunch of other heavily upvoted features.

martin19 avatar Feb 05 '22 16:02 martin19

How you see the problem (based on replies) From the answers of the contributors I can decipher what you think on the benefits of the final keyword:

  • prevent extending a class (not methods)
  • optimize class
  • constraining mutability

Another aspect: OOP design As others have mentioned the use of final keyword especially on methods is a necessary tool to build OOP programs.

I want to cite an chapter title from Joshua Bloch's Effective Java:

"Design and document for inheritance or else prohibit it"

This chapter builds on the well known open-closed principle which is supported by TypeScript. If you write a class and you wan't your users to build on it you allow them to extend the class. Why? Because then it will be useful in countless ways! But if you can't protect your base class's invariants you open up the way for countless mistakes to be made as well.

You want to prohibit extending the class as in actuality inheritance can break invariants of your base class. This is not a theoretical issue.

Real-world example: Angular I came here because I want to build an Angular component with an abstract class, with the the abstract methods being the only extensions points. As my base class implements Angular life-cycle hooks, which of course can't be private, I want to prevent children components to mistakenly disable the functionality of my abstract base class. If they override these life-cycle hooks my component won't be able to provide its functionality at all!

flash42 avatar Feb 08 '22 18:02 flash42

Hi. I respect the comment in https://github.com/microsoft/TypeScript/issues/9264#issuecomment-540713479 that this request isn't going to be relitigated. I scanned, but did not read all the cases, so apologies if this use case has already been described.

I have this set-up:

interface Interface {
  canFoo(): boolean;
}

class Base implements Interface {
  public canFoo() { return true; }
}

class Instance extends Base {
  public canFoo() { conditions...; }
}

There are somewhere between 300-400 subclasses of Base, many of them have their own canFoo().

There is also a controller of sorts which does a lot of the things that should be in a common canFoo type situation. So 90% of the reasons an instance can Foo is because the controller is checking it separately. So for the sake of clarity, I'd like to move all of that onto Base.

interface Interface {
  canFoo(): boolean;
}

class Base implements Interface {
  public abstract moreCanFoo() {
    return true;
  }

  public final canFoo() {
    if (!common-conditions) return false;
    return this.moreCanFoo();
  }
}

class Instance extends Base {
  public moreCanFoo() { conditions...; }
}

If Base.canFoo is not final, I can accidentally forget to rename the Instances' canFoos, creating new issues.

Edited to add I acknowledge this is solvable other ways, like renaming all the canFoos first. But I like when the compiler works for me. It brings me confidence.

kberg avatar Aug 17 '22 05:08 kberg

Consider to reopen. Prevent methods from override with the final or sealed (or existing readonly?) keyword. It's weird that this issue has been closed as it has no positive impact on runtime. See post / close reason. It's TypeScript. It's not about runtime. It's about hints to prevent a class method from override. Either the whole class or single method. Runtime does not matter. Like the most stuff in TypeScript. Like private or override. It's also about type definition files for e.g. APIs.

class MyService {
  public getConfig() {
     // Override me.
  }

  public start() {
    const config = this.getConfig();
    // Get config and do stuff. But don't override me. Needs a keyword to prevent from overriding.
  }
}

https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/sealed

infacto avatar Aug 26 '22 11:08 infacto