Skip to content

Instantly share code, notes, and snippets.

@nunof07
Last active July 21, 2023 23:07
Show Gist options
  • Save nunof07/cb7e405ed2013c6af80f57c9bf95af6f to your computer and use it in GitHub Desktop.
Save nunof07/cb7e405ed2013c6af80f57c9bf95af6f to your computer and use it in GitHub Desktop.
TypeScript final and frozen class decorators
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
/**
* 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);
}
};
}
/**
* Freeze constructor and prototype.
* @param target Target.
*/
export function frozen(target: Function): void {
Object.freeze(target);
Object.freeze(target.prototype);
}
@nunof07
Copy link
Author

nunof07 commented Oct 28, 2017

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment