Created
October 6, 2022 13:08
-
-
Save maxgfr/de6a3c8e16051521cb84e5bf0ee0554e to your computer and use it in GitHub Desktop.
Name decorator
This file contains hidden or 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
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