Skip to content

Instantly share code, notes, and snippets.

@maxgfr
Created October 6, 2022 13:08
Show Gist options
  • Save maxgfr/de6a3c8e16051521cb84e5bf0ee0554e to your computer and use it in GitHub Desktop.
Save maxgfr/de6a3c8e16051521cb84e5bf0ee0554e to your computer and use it in GitHub Desktop.
Name decorator
export const nameKey = Symbol("name");
/**
* To perserve class name though mangling.
* @example
* @name('Customer')
* class Customer {}
* @param className
*/
export function name(className: string): ClassDecorator {
return Reflect.metadata(nameKey, className) as ClassDecorator;
}
/**
* @example
* const type = Customer;
* getName(type); // 'Customer'
* @param type
*/
export function getName<T extends object>(type: T): string {
return Reflect.getMetadata(nameKey, type) as string;
}
/**
* @example
* const instance = new Customer();
* getInstanceName(instance); // 'Customer'
* @param instance
*/
export function getInstanceName(instance: Record<string, unknown>): string {
return Reflect.getMetadata(nameKey, instance.constructor) as string;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment