TypeScript icon indicating copy to clipboard operation
TypeScript copied to clipboard

Use of generics with typeof keyword

Open Anupheaus opened this issue 11 years ago • 4 comments

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.

Anupheaus avatar Dec 05 '14 10:12 Anupheaus

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);

sccolbert avatar Dec 05 '14 14:12 sccolbert

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?

Anupheaus avatar Dec 05 '14 15:12 Anupheaus

See #204 and the linked thread there.

RyanCavanaugh avatar Dec 06 '14 18:12 RyanCavanaugh

Related issue: #4775

omidkrad avatar Sep 14 '15 17:09 omidkrad