Use of generics with typeof keyword
This is more of a suggestion (and please forgive me if this is not where they are supposed to be submitted), which may or may not even be feasible.
I'd like it to be possible for generic types to be used with the typeof keyword, so you could do this for example:
function ofType<U>(type: typeof U): U {
}
...or...
function create<U>(typeof U, ...args: Array<any>): U {
}
But at the moment, VS complains about U with the typeof keyword stating that it can't find the name U. The real point of this is that the generic U is inferred from the type provided, rather than having to specify the type twice so that the result is that I can do this:
var typedMyTypeInstance = create(MyType, ...some args...);
...rather than this...
var typedMyTypeInstance = create<MyType>(MyType, ...some args...);
I know it is a minor thing to have to write it twice, but when you have a type deep in to a namespace, this line can get very long.
Ideally I'd like to be able to do this:
var typedMyTypeInstance = create<MyType>(...some args...);
But I understand that the generic type is more of an intellisense directive than a javascript entity and so I can't use it within the javascript function because it doesn't exist when the script behind is executed.
I've done this using the following pattern:
interface IClass<T> {
new (...args: any[]): T;
}
class Foo { }
function factory<T>(type: IClass<T>): T {
return new type();
}
var f = factory(Foo);
That works brilliantly thank you! Should this be left as a suggestion though because as brilliant as this is, it is a bit of a (I hate to use this word but) hack to make it work I think?
See #204 and the linked thread there.
Related issue: #4775