TypeScript icon indicating copy to clipboard operation
TypeScript copied to clipboard

Automate reflection-style generic functions

Open BSick7 opened this issue 11 years ago • 3 comments

In C#, you can create a generic method that is aware of the generic types.

T As<T>(obj: object)
{
    return obj as T;
}

In typescript, you must specify the type twice to accomplish the same.

function as<T>(obj: any, _T: any): T {
    return (obj instanceof _T) ? obj : null;
}

It would be nice to automate this for strictly class types (not interfaces since it's not possible).

function as<T>(obj: any): T {
    return (obj instanceof T) ? obj : null;
}

BSick7 avatar Dec 15 '14 15:12 BSick7

TypeScript can't infer the class constructor from the class type, but it can infer the type from the constructor:

function as<T>(obj: any, T: new(...args: any[]) => T): T {
    return (obj instanceof T) ? obj : null;
}
var d = as({}, Date); // inferred as type Date

jeffreymorlan avatar Dec 16 '14 04:12 jeffreymorlan

I was posing an example where you would have to explicitly specify the generic type T.

var obj  = new Date();
var d = as<Date>(obj);

BSick7 avatar Dec 16 '14 13:12 BSick7

The problem is there's no 1:1 correspondence between types and the constructor functions that make them. This is similar to #204 in that we don't have any way to know that the Date constructor function was actually the creator of the Date type.

RyanCavanaugh avatar Dec 16 '14 19:12 RyanCavanaugh