Skip to content

Instantly share code, notes, and snippets.

@jeremyben
Last active August 1, 2019 13:16
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 jeremyben/06e821f97ceefe23f7e072741241faba to your computer and use it in GitHub Desktop.
Save jeremyben/06e821f97ceefe23f7e072741241faba to your computer and use it in GitHub Desktop.
Make new keyword optional.
/**
* 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