Last active
August 1, 2019 13:16
-
-
Save jeremyben/06e821f97ceefe23f7e072741241faba to your computer and use it in GitHub Desktop.
Make new keyword optional.
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
/** | |
* Gives a class constructor the possibility to be invoked | |
* with or without the `new` keyword, like built-in constructors. | |
* | |
* @param class_ class whose constructor will be proxified. | |
* @param constructorName if we need an accurate `constructor.name` property. | |
*/ | |
export function makeNewOptional<C extends new (...args: any[]) => any>(class_: C, constructorName?: string) { | |
type NoNew<T extends C> = (...args: ConstructorParameters<T>) => InstanceType<T> | |
const proxy = new Proxy(class_, { | |
apply(target, this_, args) { | |
return new target(...args) | |
}, | |
}) as (C & NoNew<C>) | |
if (constructorName) Object.defineProperty(proxy, 'name', { value: constructorName }) | |
return proxy | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment