Support final classes (non-subclassable)
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
Implement Final Class Support in TypeScript
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
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.
typescriptfunction final(target: Function) { Object.freeze(target); } - 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
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
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.
typescriptdescribe('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
Alex Chen
2450 rep