FG
๐ŸŒ Web & Full-StackMicrosoft

Support final classes (non-subclassable)

Freshabout 19 hours ago
Mar 14, 20260 views
Confidence Score95%
95%

Problem

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: [code block]

Error Output

Error: foo is final and cannot be extended

Unverified for your environment

Select your OS to check compatibility.

1 Fix

Canonical Fix
Unverified Fix
New Fix โ€“ Awaiting Verification

Implement Final Class Support in TypeScript

Medium Risk

TypeScript currently does not have a built-in mechanism to prevent classes from being subclassed. This can lead to unintended inheritance, which may violate design principles and lead to bugs. The absence of a 'final' keyword means that developers cannot enforce class immutability in terms of inheritance.

Awaiting Verification

Be the first to verify this fix

  1. 1

    Define a Final Class Decorator

    Create a decorator that marks a class as final. This decorator will be used to track classes that should not be subclassed.

    typescript
    function final(target: Function) { Object.freeze(target); }
  2. 2

    Modify the Compiler to Check for Final Classes

    Enhance the TypeScript compiler to check if a class is decorated with the final decorator and throw an error if another class attempts to extend it.

    typescript
    // Pseudo-code for compiler modification
    if (isFinalClass(baseClass)) {
        throw new Error(`${baseClass.name} is final and cannot be extended`);
    }
  3. 3

    Update Documentation

    Document the usage of the final decorator and the behavior of the TypeScript compiler when it encounters a final class.

    typescript
    // Example usage:
    @final
    class MyClass {}
    class MySubClass extends MyClass {} // This should trigger an error
  4. 4

    Test the Implementation

    Create unit tests to ensure that the final decorator works as expected and that the compiler correctly identifies attempts to subclass final classes.

    typescript
    describe('Final Class Tests', () => {
        it('should throw error when subclassing final class', () => {
            expect(() => new MySubClass()).toThrowError('MyClass is final and cannot be extended');
        });
    });

Validation

To confirm the fix worked, create a final class using the decorator and attempt to subclass it. The TypeScript compiler should throw an error indicating that the class cannot be extended. Additionally, run the unit tests to ensure all scenarios are covered.

Sign in to verify this fix

Environment

Submitted by

AC

Alex Chen

2450 rep

Tags

typescriptcompilerwon't-fixsuggestion