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 get enough courage and free time on my hands, I'll check how they implement abstract and implement final myself

Fine, I'll do it myself - Thanos

Voltra avatar Feb 28 '26 21:02 Voltra

@Voltra yes but your pr won’t be accepted and your work rolled back « Endgame ». You better convince ecma script to add final.

Xample avatar Mar 01 '26 07:03 Xample

I implemented it myself using a decorator and ESLint rules, in case anyone is interested:

Decorator: https://www.npmjs.com/package/final-decorator ESLint rules checking decorator: https://www.npmjs.com/package/eslint-plugin-final

Check the repo for how to use it: https://github.com/TiMESPLiNTER/ts-final

import { Final } from 'final-decorator';

@Final
class FinalBase {
  keep(): void {}
}

class Child extends FinalBase { // ❌ Class FinalBase is marked with @Final and cannot be extended.
  keep(): void {}
}

class FinalMethodBase {
    @Final
    keep(): void {}
}

class ChildOfFinalMethodBase extends FinalMethodBase {
    keep(): void {} // ❌ Method keep overrides a base method marked with @Final.
}

//
// Not allowed
//
@Final
class FinalFinal {
  @Final // ❌ Method-level @Final is redundant when the class is already marked with @Final.
  keep(): void {}
}

@Final // ❌ Final is not allowed on abstract classes.
abstract class AbstractBase {
  abstract run(): void;
}

TiMESPLiNTER avatar Mar 14 '26 13:03 TiMESPLiNTER

From what I've gathered, the last comments from the Typescript team are 6+ years old, including in the duplicate/related tickets.

In the meantime, there's been

Which all point towards a wider adoption of classes and OOP concepts in js, especially around extendability contract.

As a bonus, we also now have:

  • LLMs running rampant on codebases, who could definitely use a syntactic keyword that conveys intentionality

Since 6 years is an eternity ago in software, it'd be valuable to know: Where does the Typescript team stand on this issue in 2027?

@RyanCavanaugh 🙏

ClementValot avatar Nov 21 '26 15:11 ClementValot