Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

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