Closed as not planned
Description
Bug Report
Using decorators and proxies it's now possible to elegantly create classes which don't require the new
keyword for instantiation. Unfortunately TypeScript doesn't allow this.
🔎 Search Terms
decorators, class decorators
🕗 Version & Regression Information
- Tested in 'Nightly' version
⏯ Playground Link
Playground link with relevant code
💻 Code
type Callable<T extends new (...args: any) => any> = T & ((...args: ConstructorParameters<T>) => InstanceType<T>);
function makeCallable<C extends new (...args: any) => any> (clazz: C): Callable<C> {
return new Proxy(clazz, {
apply (target, thisArg, argArray) {
return new target(...argArray);
},
}) as unknown as Callable<C>;
}
function callable<C extends new (...args: any) => any> (clazz: C, context: ClassDecoratorContext<C>): Callable<C> {
return makeCallable(clazz);
}
// Using function
const User = makeCallable(class {
constructor (name: string, age?: number) {}
});
const x = new User('foo');
console.log(x instanceof User);
const y = User('bar'); // works
console.log(y instanceof User);
// Using decorator
@callable
class DecoratedUser {
constructor (name: string, age?: number) {}
}
const a = new DecoratedUser('foo', 19);
console.log(a instanceof DecoratedUser);
const b = DecoratedUser('bar', 12); // Value of type 'typeof DecoratedUser' is not callable.
console.log(b instanceof DecoratedUser);
🙁 Actual behavior
TypeScript does not allow for the proxied class to be called, although this is valid js code and all instanceof checks are passing.
🙂 Expected behavior
TypeScript should use the return type of the decorator as the new type for the class.