Skip to content

Instantly share code, notes, and snippets.

@Parables
Forked from nunof07/example.ts
Created December 21, 2022 17:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Parables/61dfb31fe4fa372fd74a7fa7898a9f50 to your computer and use it in GitHub Desktop.
Save Parables/61dfb31fe4fa372fd74a7fa7898a9f50 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);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment