Last active
July 21, 2023 23:07
-
-
Save nunof07/cb7e405ed2013c6af80f57c9bf95af6f to your computer and use it in GitHub Desktop.
TypeScript final and frozen class decorators
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { final } from './final.ts'; | |
import { frozen } from './frozen.ts'; | |
@final | |
@frozen | |
export class Example { | |
} | |
export class ExampleSub extends Example { | |
} | |
const isFrozen = Object.isFrozen(Example); // true | |
new ExampleSub(); // errror thrown |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Prevent instances from inherited classes. | |
* @param target Target. | |
*/ | |
export function final<T extends { new (...args: any[]): object }>(target: T): T { | |
return class Final extends target { | |
constructor(...args: any[]) { | |
if (new.target !== Final) { | |
throw new Error('Cannot inherit from final class'); | |
} | |
super(...args); | |
} | |
}; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Freeze constructor and prototype. | |
* @param target Target. | |
*/ | |
export function frozen(target: Function): void { | |
Object.freeze(target); | |
Object.freeze(target.prototype); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
More info here: http://www.broculos.net/2017/10/typescript-final-class-decorator.html#.WfSiLWhSyUk