New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Suggestion: Syntax for constructor signature #4775
Comments
What about constructors that have a defined argument signature? |
@kitsonk in that case you can use exact constructor signature like |
Then that would seem "auto-magic" to me and surprising... "if you have this one signature you can use this one keyword in these scenarios, but if you have anything else..." |
The var x: number;
function foo<x>(b: typeof x) { } I would suggest defining a generic type that represents a constructor: interface Constructor<T> {
new (...args: any[]): T;
}
declare class EventAggregator
{
subscribe<T>(event: Constructor<T>, callback: (message: T) => void): void;
publish<T>(event: Constructor<T>): void;
} |
@kitsonk that was the point of my suggestion, to define type of constructor with arbitrary arguments. @ahejlsberg the However, I wonder what class ClassX {}
class ClassY {}
function foo<x>(b: typeof ClassX) { }
foo(ClassX);
foo(ClassY); |
You have no members in class ClassX { x; }
class ClassY { y; }
function foo<x>(b: typeof ClassX) { }
foo(ClassX);
foo(ClassY); // Error |
OK, that makes sense. Now what makes class ClassX { x; }
class ClassY { y; }
function foo(b: typeof ClassX, c: ClassX) { }
foo(ClassX, new ClassX);
function bar<T>(b: typeof T, c: T) { } // Error
bar(ClassY, new ClassY); |
|
An easy rule of thumb is: When |
This is a valid signature:
I would like to suggest to support
typeof T
to be equivalent of{ new(...any): T; }
above.which in my opinion is much more expressive. Notice that if we used
typeof SomeClass
compiler would accept it. So why not also accepttypeof T
?Here's an example:
Workarounds that don't work really
Using generic type of
T extends Function
orFunction
instead ofT
breaks type inference ofT
The text was updated successfully, but these errors were encountered: